Last active
January 12, 2016 12:03
-
-
Save Loki-Astari/394661d4c5e36aa8cc02 to your computer and use it in GitHub Desktop.
Test for reversing a string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <ctime> | |
#include <iostream> | |
void r2(std::string& source) | |
{ | |
// Step 1: reverse the string. | |
std::reverse(std::begin(source), std::end(source)); | |
// Step 2: Reverse each word in the string. | |
// This puts them back the correct way around | |
auto const end = std::end(source); // The very end | |
auto back= std::begin(source); // One past the end of the last word | |
auto next= back; // The start of the next word | |
// Loop over the string finding words. | |
for(auto item = next; back != end; item = next) { | |
back = std::find(item, end, '.'); | |
std::reverse(item, back); // Reverse a found word. | |
next = back + 1; | |
} | |
} | |
void r1(std::string& source) | |
{ | |
std::string result; | |
size_t source_length = source.size(); | |
size_t end = source_length; | |
// Loop from end of string to reverse the domains | |
for (int i = source_length; i >= 0; i--) { | |
// If not domain divider, continue | |
if (source[i] != '.') { | |
continue; | |
} | |
// Append the domain substring | |
result.append(source, i+1, end - i); | |
result += '.'; // Append divider | |
end = i-1; // Set end point of next domain | |
} | |
// Copy the last bit of source string, if needed | |
if ((end = result.size()) != source_length) { | |
result.append(source, 0, source_length - end); | |
} | |
source = std::move(result); | |
} | |
int main() | |
{ | |
std::string test = "this.is.a.subdomain"; | |
std::cout << std::time(nullptr) << "\n"; | |
for(int loop=0;loop < 100'000'000; ++loop) { | |
r1(test); | |
} | |
std::cout << std::time(nullptr) << "\n"; | |
for(int loop=0;loop < 100'000'000; ++loop) { | |
r2(test); | |
} | |
std::cout << std::time(nullptr) << "\n"; | |
} | |
> g++ -O3 -std=c++1z pl.cpp | |
> ./a.out | |
1449457676 | |
1449457686 | |
1449457689 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment