Created
February 16, 2012 19:04
-
-
Save cslarsen/1847054 to your computer and use it in GitHub Desktop.
Reverse string in "canonical" C++
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
/* | |
* Reverse string in "canonical" C++ | |
* | |
* Why did I make this a gist? Because I've seen so | |
* many cumbersome ways of doing this in C++, including | |
* using <algorithm> and std::reverse, using loops and | |
* so on. Yeah, those work too, and loops are fine for | |
* C, but in C++, you should simply just use the iterators | |
* and standard constructors that std::string gives you. | |
* | |
* Source: Christian Stigen Larsen | |
* http://csl.sublevel3.org | |
*/ | |
#include <iostream> | |
#include <string> | |
/* | |
* Reverse a std::string in C++. | |
* No need for <algorithm> or c_str()-wrangling. | |
* | |
*/ | |
std::string reverse(const std::string& s) | |
{ | |
return std::string(s.rbegin(), s.rend()); | |
} | |
int main() | |
{ | |
// Outputs "!dlrow ,olleH" | |
std::cout << reverse("Hello, world!") << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you do want to do it in place, though, you could do: