C ++ std :: transform()和toupper()..这样做失败? [英] C++ std::transform() and toupper() ..why does this fail?

查看:197
本文介绍了C ++ std :: transform()和toupper()..这样做失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2 std :: string。我只想输入字符串:

I have 2 std::string. I just want to, given the input string:


  1. 大写每个字母

  2. 到输出字符串。

这是如何工作的:

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


推荐答案

out 中没有空格。C ++算法不会自动增长目标容器,您必须自己创建空间,或使用插入适配器。

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

另一个选择是创建

std :: string out(s.length(),'X');

这篇关于C ++ std :: transform()和toupper()..这样做失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆