Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse an std::string? [duplicate]

Im trying to figure out how to reverse the string temp when I have the string read in binary numbers

istream& operator >>(istream& dat1d, binary& b1)     {                   string temp;       dat1d >> temp;     } 
like image 948
Kameron Spruill Avatar asked Feb 09 '11 23:02

Kameron Spruill


People also ask

How do you reverse copy a string in C++?

Using reverse() function in C++ The built-in reverse function reverse() in C++ directly reverses a string. Given that both bidirectional begin and end iterators are passed as arguments.


2 Answers

I'm not sure what you mean by a string that contains binary numbers. But for reversing a string (or any STL-compatible container), you can use std::reverse(). std::reverse() operates in place, so you may want to make a copy of the string first:

#include <algorithm> #include <iostream> #include <string>  int main() {     std::string foo("foo");     std::string copy(foo);     std::cout << foo << '\n' << copy << '\n';      std::reverse(copy.begin(), copy.end());     std::cout << foo << '\n' << copy << '\n'; } 
like image 133
Max Lybbert Avatar answered Sep 20 '22 18:09

Max Lybbert


Try

string reversed(temp.rbegin(), temp.rend()); 

EDIT: Elaborating as requested.

string::rbegin() and string::rend(), which stand for "reverse begin" and "reverse end" respectively, return reverse iterators into the string. These are objects supporting the standard iterator interface (operator* to dereference to an element, i.e. a character of the string, and operator++ to advance to the "next" element), such that rbegin() points to the last character of the string, rend() points to the first one, and advancing the iterator moves it to the previous character (this is what makes it a reverse iterator).

Finally, the constructor we are passing these iterators into is a string constructor of the form:

template <typename Iterator> string(Iterator first, Iterator last); 

which accepts a pair of iterators of any type denoting a range of characters, and initializes the string to that range of characters.

like image 29
HighCommander4 Avatar answered Sep 24 '22 18:09

HighCommander4