c++ - for_each 将字符串连接到 vector 中的所有字符串

标签 c++ c++11

我正在学习 C++,所以很自然地我一直在胡闹,试图弄清楚我能做什么,不能做什么。我写了一小段代码来处理 lambda 和字符串,但它似乎给我带来了一些问题 :S。

我在 vector 中存储了两个字符串,一个是巧克力,另一个是 Vanilla 。我想将软糖连接到最后。我正在声明关联的库。一切都编译并运行。但没有任何连接 :S 任何帮助将不胜感激。提前致谢。

void main()
{

     vector<string> ramzy;
     ramzy.push_back("chocolate");
     ramzy.push_back("vanilla");

     for_each(ramzy.begin(),ramzy.end(),
         [](string word)->string{
             string i = word + " fudge";
             return (i);
         } );

     cout << ramzy[0] << endl << ramzy[1] << endl;

}

输出如下:

chocolate
vanilla

期望的输出如下所示:

Chocolate Fudge
Vanilla Fudge

最佳答案

来自 reference :

std::for_each

Applies the given function object f to the result of dereferencing every iterator in the range [first, last), in order. If InputIt is a mutable iterator, f may modify the elements of the range through the dereferenced iterator. If f returns a result, the result is ignored.

因此,您必须将 lambda 更改为:

[](string& word)
{
    word += " fudge";
}

关于c++ - for_each 将字符串连接到 vector 中的所有字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17078339/

相关文章:

c++ - 在可变参数模板类中初始化静态数组

c++ - 视频录制在 IMFSinkWriter->Finalize() 上挂起;

c++ - 如何分析我自己的 C++ 共享库

c++ - 无法链接到 quantlib

c++ - 这会被视为访问器吗? (C++)

c++ - 检查元素是否在 std::initializer_list 中

c++ - 无法在 Boost.Log 中设置控制台日志的格式

c++ - std::partition 分割对象类型的 vector 时出错

带有数据存储库的 C++ Bazel 项目

c++ - 非惰性/短路 bool 运算符,强制计算两个参数