String won't reverse using reverse_copy

The string you are trying to copy into is too short (zero length). You have to make it long enough to accept the copied data:

std::string A = "abc";
std::string B;
B.resize(A.size()); // make B big enough

std::reverse_copy(A.begin(), A.end(), B.begin());

std::cout << B << '\n';

Currently you are writing past the end of B causing undefined behavior.

Another way to do this is to use a special iterator called std::back_insert_iterator, which pushes characters to the back of the target string:

std::string A = "abc";
std::string B;

std::reverse_copy(A.begin(), A.end(), std::back_inserter(B));

The std::back_inserter() function returns a std::back_insert_iterator for the string you provide as a parameter (or any container that implements push_back(), such as std::string::push_back()).

Note: std::reverse_copy invoked with standard std::string iterators (as in this example) will simply reverse the code units of a string and not necessarily the characters (depending on the encoding). For example a UTF-8 encoded string that contains multibyte characters would not be reversed correctly by this function as the multibyte sequences would also be reversed making them invalid.


std::reverse_copy doesn't allocate space, so your code leads to undefined behavior. Either allocate space beforehand:

string A = "abc";
string B;
B.resize(A.size());
reverse_copy(A.begin(),A.end(),B.begin());
cout<<B<<endl;

or use std::back_inserter:

string A = "abc";
string B;
reverse_copy(A.begin(),A.end(),std::back_inserter(B));
cout<<B<<endl;

std::reverse_copy expects there to be pre-allocated space in the destination, so you want something like:

std::string a = "abc";
std::string b(a.size(), ' ');
std::reverse_copy(std::begin(a), std::end(a), std::begin(b);
std::cout << b << "\n";

Tags:

C++