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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)