字符串不会使用 reverse_copy 反转

String won't reverse using reverse_copy

本文关键字:copy 反转 reverse 字符串      更新时间:2023-10-16

如果我有一个等于"abc"的字符串A,并且我想有字符串B是字符串A的反向形式,为什么我不能使用reverse_copy()来执行此操作?

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

reverse_copy()可以与字符串一起使用吗?reverse()似乎有效。

您尝试复制到的string太短(零长度)。您必须使其足够长以接受复制的数据:

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';

当前,您正在写入超过B末尾,从而导致未定义的行为

另一种方法是使用一个名为std::back_insert_iterator的特殊迭代器,它将字符推送到目标字符串的后面:

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

std::back_inserter()函数返回您作为参数提供的字符串(或任何实现push_back()的容器,例如std::string::push_back())的std::back_insert_iterator

注意:使用标准std::string迭代器调用的 std::reverse_copy 将简单地反转字符串的代码单元而不一定是字符(取决于编码)。例如,包含多字节字符的UTF-8编码字符串不会被此函数正确反转,因为多字节序列也会被反转,使其无效。

std::reverse_copy

不分配空间,因此您的代码会导致未定义的行为。事先分配空间:

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

或使用std::back_inserter

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

std::reverse_copy期望目标中有预先分配的空间,因此您需要类似以下内容:

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";