HunderingThooves
HunderingThooves

Reputation: 992

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 << 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!

Upvotes: 7

Views: 22196

Answers (4)

C. K. Young
C. K. Young

Reputation: 223003

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!

Upvotes: 8

Mahesh
Mahesh

Reputation: 34625

Using std::reverse is easier.

std::reverse( source.begin(), source.end() ); // source is of type std::string

Upvotes: 4

templatetypedef
templatetypedef

Reputation: 372764

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;
}

Upvotes: 2

Benjamin Lindley
Benjamin Lindley

Reputation: 103693

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());

Upvotes: 20

Related Questions