0

The following code prints an empty string and i am unable to understand why it is so?

#include <string>
#include <algorithm>
#include <iostream>

int main()
{
    std::string s="hello";
    std::string r;
    std::copy(s.rbegin(),s.rend(), r.begin());
    std::cout<<r;
    return 0;
}
Argha Sen
  • 81
  • 7
  • No i am not looking to copy to a vector of chars. I am looking at copying the string to another string. I am aware of other string copying mechanisms but i expected this to work as well. – Argha Sen Aug 16 '20 at 13:42
  • 1
    `std::copy` doesn't allocate memory. You have the resize the container. You can `std::string r(s.length(), '\0');` – Thomas Sablik Aug 16 '20 at 13:45
  • 1
    Because `r` is empty, and the only thing that can be copied into an empty string is another empty string. Is there any specific reason why `r=s;` will not work for you? – Sam Varshavchik Aug 16 '20 at 13:46
  • There's also a constructor for `std::string` that uses iterators. You can do `std::string r(s.rbegin(), s.rend());` to get this effect, bypassing `std::copy`. – JohnFilleau Aug 16 '20 at 13:49
  • @sam varshachik i was doing it more as a learning experience – Argha Sen Aug 16 '20 at 13:51

1 Answers1

6

The problem is r is an empty std::string, it contains no chars. std::copy is trying to copy-assign chars since r.begin(), which leads to UB.

You can make r containing 5 elements in advance.

std::string r(5, '\0');

Or

std::string r;
r.resize(5);

Or use std::back_inserter.

std::string r;
std::copy(s.rbegin(),s.rend(), std::back_inserter(r));
songyuanyao
  • 169,198
  • 16
  • 310
  • 405