我正在尝试使用 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/