字符串不会使用 reverse_copy 反转
String won't reverse using reverse_copy
如果我有一个等于"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";
相关文章:
- 如何反转整数参数包
- 使用用户定义函数的字符串反转
- std::filesystem::copy throws filesystem_error
- 在C++中使用Cstring反转字符串
- 如何在 Boost.Asio 中使用 Zero-copy sendmsg/receive
- 需要反转音频步进公式
- 我的逻辑反转字符串中的元音有什么问题?
- 有人可以解释一下这段代码如何能够反转字符串
- 反转依赖于 end() 的迭代器
- 为什么我的 LEGACY OPENGL 颜色反转了?
- 使用 TreeSet Java 对反转进行计数
- 如何反转我的输入,包括否定
- 反转整数的一部分(一半)的函数
- 反转阵列中的正序列
- 反转C++ foo(MyClass &) vs foo(const MyClass &)
- 试图(稍微)概括C++模板.关联容器键:值反转
- 如何在C++中反转文本文件中字符的顺序?
- 反转后不返回最后一个元素
- 整数的反转位
- C++ for 循环,用于反转数字 10 - 99