C++ std::transform() 和 toupper() ..为什么会失败?
我有 2 个 std::string。我只想,给定输入字符串:
- 将每个字母大写,
- 将大写字母分配给输出字符串。
为什么这个可以工作:
std::string s="hello";
std::string out;
std::transform(s.begin(), s.end(), std::back_inserter(out), std::toupper);
但是却不行(导致程序崩溃)?
std::string s="hello";
std::string out;
std::transform(s.begin(), s.end(), out.begin(), std::toupper);
因为这有效(至少在同一个字符串上:
std::string s="hello";
std::string out;
std::transform(s.begin(), s.end(), s.begin(), std::toupper);
I have 2 std::string. I just want to, given the input string:
- capitalize every letter
- assign the capitalized letter to the output string.
How come this works:
std::string s="hello";
std::string out;
std::transform(s.begin(), s.end(), std::back_inserter(out), std::toupper);
but this doesn't (results in a program crash)?
std::string s="hello";
std::string out;
std::transform(s.begin(), s.end(), out.begin(), std::toupper);
because this works (at least on the same string:
std::string s="hello";
std::string out;
std::transform(s.begin(), s.end(), s.begin(), std::toupper);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
out
中没有空格。 C++ 算法不会自动增长其目标容器。您必须自己腾出空间,或使用插入器适配器。要在
out
中腾出空间,请执行以下操作:out.resize(s.length());
[编辑] 另一种选择是使用以下命令创建具有正确大小的输出字符串构造函数。
std::string out(s.length(), 'X');
There is no space in
out
. C++ algorithms do not grow their target containers automatically. You must either make the space yourself, or use a inserter adaptor.To make space in
out
, do this:out.resize(s.length());
[edit] Another option is to create the output string with correct size with this constructor.
std::string out(s.length(), 'X');
我想说的是,out.begin() 返回的迭代器在空字符串的几次增量之后无效。在第一个
++
之后是==out.end()
,然后下一个增量之后的行为是未定义的。毕竟这正是插入迭代器的用途。
I'd say that the iterator returned by
out.begin()
is not valid after a couple of increments for the empty string. After the first++
it's==out.end()
, then the behavior after the next increment is undefined.After all this exactly what insert iterator is for.
这就是后插入器的意义:它将元素插入到容器中。使用 begin(),您可以将迭代器传递给空容器并修改无效的迭代器。
抱歉 - 我的编辑干扰了您的评论。我第一次发帖是不小心写错了。
Thats the sense of a backinserter: It inserts elements to a container. using begin(), you pass a iterator to a empty container and modify invalid iterators.
I am sorry - my edits interfered with your comments. I first posted something wrong accidentally.