简体   繁体   中英

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!

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!

使用std :: reverse更容易。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM