Dlaczego nie mogę użyć std :: copy ze std :: string do innego std :: string? [duplikować]
Aug 16 2020
Poniższy kod drukuje pusty ciąg i nie mogę zrozumieć, dlaczego tak jest?
#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;
}
Odpowiedzi
5 songyuanyao Aug 16 2020 at 20:46
Problem jest r
pusty std::string
, nie zawiera char
s. std::copy
próbuje skopiować-przypisać char
s od r.begin()
, co prowadzi do UB.
Możesz zrobić r
z wyprzedzeniem 5 elementów.
std::string r(5, '\0');
Lub
std::string r;
r.resize(5);
Lub użyj std::back_inserter
.
std::string r;
std::copy(s.rbegin(),s.rend(), std::back_inserter(r));