我正在学习 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. IfInputIt
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/