If I have a string A
that equals "abc"
and I want to have string B
that is the reversed form of string A
, why can't I use reverse_copy()
to do this ?
std::string A = "abc"; std::string B; std::reverse_copy(A.begin(), A.end(), B.begin()); std::cout << B << std::endl; // no output
Is reverse_copy()
usable with strings? reverse()
seems to work.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With