我正在尝试使用 for_each 而不是普通的 for 循环。但是,由于我是 C++11 的新手,所以我有点卡住了。我的意图是同时使用 for_each 和 lambda 表达式。有任何想法吗 ?我正在使用 Visual Studio 2010。
问候,
Atul
这是代码。
#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;
}