C++ std::transform() 和 toupper() ..为什么会失败?

发布于 2024-08-06 05:34:57 字数 575 浏览 4 评论 0原文

我有 2 个 std::string。我只想,给定输入字符串:

  1. 将每个字母大写,
  2. 将大写字母分配给输出字符串。

为什么这个可以工作:

  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:

  1. capitalize every letter
  2. 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

美人如玉 2024-08-13 05:34:57

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

帅哥哥的热头脑 2024-08-13 05:34:57

我想说的是,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.

倾城月光淡如水﹏ 2024-08-13 05:34:57

这就是后插入器的意义:它将元素插入到容器中。使用 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文