c++ - 如何在 for_each 中使用 lambda?

标签 c++ lambda foreach c++11

我正在尝试使用 for_each 而不是普通的 for 循环。然而,由于我是 C++11 的新手,我有点卡住了。我的意图是一起使用 for_each 和 lambda 表达式。有任何想法吗 ?我正在使用 visual studio 2010。
此致,
阿图尔

这是代码。

#include "stdafx.h"  
#include <algorithm>  
#include <memory>  
#include <vector>  
#include <iostream>

using namespace std;  

struct Point  
{
    union 
    {
        double pt[3];
        struct {double X,Y,Z;};
        struct {double x,y,z;};
    };

    Point(double x_,double y_,double z_)
      :x(x_),y(y_),z(z_)
    {}
    Point()
      :x(0.0),y(0.0),z(0.0)
    {}

    void operator()()
    {
        cout << "X coordinate = " << x << endl;
        cout << "Y coordinate = " << y << endl;
        cout << "Z coordinate = " << z << endl;
    }
};  

int _tmain(int argc, _TCHAR* argv[])  
{  
    std::vector<Point> PtList(100);

    //! the normal for loop
    for(int i = 0; i < 100; i++)
    {
        // Works well  
        PtList[i]();
    }

    //! for_each using lambda, not working
    int i = 0;
    for_each(PtList.begin(),PtList.end(),[&](int i)
    {
        // Should call the () operator as shown previously
        PtList[i]();
    });

    //! for_each using lambda, not working
    Point CurPt;
    for_each(PtList.begin(),PtList.end(),[&CurPt](int i)
    {
        cout << "I = " << i << endl;
        // should call the() operator of Point
        CurPt();
    });

    return 0;
}

最佳答案

for_each 的第三个参数是一个应用于每个元素 的函数,而不是每个索引。否则,在传统循环中使用它有什么意义?

因此,它采用的不是 int 参数,而是 Point 参数。现在没有理由捕获任何东西,因为对 PtList 的引用是不必要的。

// Should make operator() const as it doesn't modify anything
for_each(PtList.begin(),PtList.end(),[](Point const& p)
{
    p();
});

关于c++ - 如何在 for_each 中使用 lambda?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11502523/

相关文章:

c++ - 非常快速的序列化。随机访问 C++

function - "Combinators"的良好解释(对于非数学家)

java - 在这种情况下如何从 for 更改为 foreach?

vb.net - 对于 ListBox1 中的每个项目做一些事情然后将项目添加到 listbox2 vb

php - 父子关系树所需的递归函数?

C++/OpenCV 将相机-视频/图像 (MJPEG) 从套接字流式传输到浏览器 (Windows 8.1)

C++ 成员 "Smash::smash"不是类型名称。

c++ - 除了LAME MP3之外,还有哪些开源的C/C++音频压缩选项?

c++ - "Lambdas are cheap"- 真的吗?在什么情况下?

pandas - 我可以获取groupby apply中分组列的值吗?