Reversing a string in C++ using a reverse iterator?
I have the following code and I just can't seem to figure out a way to get the strings reversed here:
stringstream convert;
string y="";
string z="";
convert &l开发者_运维百科t;< x;
string::reverse_iterator rit;
y=convert.str();
int j=0;
for (rit = y.rbegin(); rit < y.rend(); rit++){
z[j] = *rit;
j++;
}
Can someone help me out with this? Thanks!
z.assign(y.rbegin(), y.rend());
Or you can do it upon construction:
std::string z(y.rbegin(), y.rend());
If you want to modify a string in place, use std::reverse:
std::reverse(y.begin(), y.end());
I'd do this:
stringstream convert;
convert << x;
string y(convert.str());
string z(y.rbegin(), y.rend());
return z;
No need to write a manual loop!
Using std::reverse is easier.
std::reverse( source.begin(), source.end() ); // source is of type std::string
I think that your problem is in this loop:
int j=0;
for (rit = y.rbegin(); rit < y.rend(); rit++){
z[j] = *rit;
j++;
}
Notice that you're writing into the string z
at various positions. However, you haven't actually initialized z
so that there's any elements in it, so this is writing to nonexistent locations, which results in undefined behavior.
To fix this, instead of writing to locations in z, try appending new characters to the end:
for (rit = y.rbegin(); rit < y.rend(); rit++){
z += *rit;
}
精彩评论