std::transform 使用 C++0x lambda 表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3885317/
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
std::transform using C++0x lambda expression
提问by Steve Townsend
回答by Edward Strange
std::transform(myv1.begin(), myv1.end(), myv1.begin(),
[](double d) -> double { return d * 3; });
回答by Steve Jessop
The main original motivation for using that functional style for these cases in C++ was, "aaagh! iterator loops!", and C++0x removes that motivation with the range-based for statement. I know that part of the point of the question was to find out the lambda syntax, but I think the answer to the question "How is this done in C++0x?" is:
在 C++ 中对这些情况使用这种函数式风格的主要原始动机是,“aaagh!迭代器循环!”,而 C++0x 使用基于范围的 for 语句消除了这种动机。我知道问题的一部分是找出 lambda 语法,但我认为这个问题的答案“这是如何在 C++0x 中完成的?” 是:
for(double &a : myv1) { a *= 3; }
There's no actual function object there, but if it helps you could pretend that { a *= 3; }
is a highly abbreviated lambda. For usability it amounts to the same thing either way, although the draft standard defines range-based for in terms of an equivalent for
loop.
那里没有实际的函数对象,但如果它有帮助,您可以假装这{ a *= 3; }
是一个高度缩写的 lambda。就可用性而言,无论哪种方式都是相同的,尽管草案标准根据等效for
循环定义了基于范围的 for 。
回答by GManNickG
Just do as Dario says:
就像达里奥说的那样:
for_each(begin(myv1), end(myv1), [](double& a) { a *= 3; });
for_each
is allowed to modify elements, saying it cannot is a myth.
for_each
允许修改元素,说它不能是一个神话。
回答by Dario
Using a mutable approach, we can use for_each
to directly update the sequence elements through references.
使用可变方法,我们可以for_each
通过引用直接更新序列元素。
for_each(begin(myv1), end(myv1), [](double& a) { a *= 3; });
是否
for_each
for_each
真的允许修改元素一直存在一些争论,因为它被称为“非变异”算法。What that means is for_each
isn't allowed to alter the sequenceit operates on (which refers to changes of the sequence structure- i.e. invalidating iterators). This doesn't mean we cannot modify the non-const elementsof the vector as usual - the structure itself is left untouched by these operations.
这意味着for_each
不允许改变它操作的序列(这是指序列结构的变化——即使迭代器无效)。这并不意味着我们不能像往常一样修改向量的非常量元素- 这些操作不会影响结构本身。
回答by John Dibling
Like this:
像这样:
vector<double> myv1;
transform(myv1.begin(), myv1.end(), myv1.begin(), [](double v)
{
return v*3.0;
});
回答by Elligno
I'm using VS2012 which support the C++11 bind adaptor. To bind the first element of the binary function (as bind1st use to do) you need to add an _1 (placeholder argument). Need to include the functional for bind.
我正在使用支持 C++11 绑定适配器的 VS2012。要绑定二元函数的第一个元素(如 bind1st 使用的那样),您需要添加一个 _1(占位符参数)。需要包含用于绑定的函数。
using namespace std::placeholders;
std::transform( myv1.begin(), myv1.end(), myv1.begin(),
std::bind( std::multiplies<double>(),3,_1));