C++ std::transform() 和 toupper() ..为什么会失败?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1489313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ std::transform() and toupper() ..why does this fail?
提问by sivabudh
I have 2 std::string. I just want to, given the input string:
我有 2 个 std::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);
回答by hrnt
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.
中没有空间out
。C++ 算法不会自动增长其目标容器。您必须自己制作空间,或使用插入器适配器。
To make space in out
, do this:
要在 中腾出空间out
,请执行以下操作:
out.resize(s.length());
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');
std::string out(s.length(), 'X');
回答by Michael Krelin - hacker
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.
我会说返回的迭代器out.begin()
在空字符串的几个增量之后无效。在第一个++
it's==out.end()
之后,下一个增量之后的行为是未定义的。
After all this exactly what insert iterator is for.
毕竟这正是插入迭代器的用途。
回答by RED SOFT ADAIR
Thats the sense of a backinserter: It insertselements to a container. using begin(), you pass a iterator to a empty container and modify invalid iterators.
这就是 backinserter 的意义:它将元素插入到容器中。使用 begin(),您将迭代器传递给空容器并修改无效的迭代器。
I am sorry - my edits interfered with your comments. I first posted something wrong accidentally.
很抱歉 - 我的编辑干扰了您的评论。我第一次不小心发布了一些错误的东西。