使用 C++0x lambda 表达式进行 std::transform
这在 C++0x 中是如何完成的?
std::vector<double> myv1;
std::transform(myv1.begin(), myv1.end(), myv1.begin(),
std::bind1st(std::multiplies<double>(),3));
原始问题和解决方案位于此处。
How is this done in C++0x?
std::vector<double> myv1;
std::transform(myv1.begin(), myv1.end(), myv1.begin(),
std::bind1st(std::multiplies<double>(),3));
Original question and solution is here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在 C++ 中针对这些情况使用该函数样式的主要原始动机是“aaagh!迭代器循环!”,而 C++0x 使用基于范围的 for 语句消除了该动机。我知道问题的部分目的是找出 lambda 语法,但我认为问题的答案是“这在 C++0x 中是如何完成的?”是:
那里没有实际的函数对象,但如果它有帮助,你可以假装
{ a *= 3; }
是一个高度缩写的 lambda。就可用性而言,无论哪种方式都相当于相同的事情,尽管标准草案根据等效的for
循环定义了基于范围的 for。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:
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 equivalentfor
loop.就像 Dario 所说的那样:
允许
for_each
修改元素,说不能是神话。Just do as Dario says:
for_each
is allowed to modify elements, saying it cannot is a myth.使用可变的方法,我们可以使用
for_each
通过引用直接更新序列元素。There has been some debate going on if
for_each
is actually allowed to modify elements as it's called a "non-mutating" algorithm.这意味着
for_each
不允许更改其操作的序列(指的是序列结构的更改 - 即使迭代器无效)。这并不意味着我们不能像往常一样修改向量的非常量元素 - 这些操作不会影响结构本身。Using a mutable approach, we can use
for_each
to directly update the sequence elements through references.There has been some debate going on if
for_each
is actually allowed to modify elements as it's called a "non-mutating" algorithm.What that means is
for_each
isn't allowed to alter the sequence it operates on (which refers to changes of the sequence structure - i.e. invalidating iterators). This doesn't mean we cannot modify the non-const elements of the vector as usual - the structure itself is left untouched by these operations.像这样:
Like this:
我正在使用支持 C++11 绑定适配器的 VS2012。要绑定二元函数的第一个元素(如 bind1st 所做的那样),您需要添加一个
_1(占位符参数)。需要包含绑定功能。
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.