Atu*_*tul 4 c++ foreach lambda c++11
我试图使用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;
}
Run Code Online (Sandbox Code Playgroud)
R. *_*des 12
第三个参数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();
});
Run Code Online (Sandbox Code Playgroud)
你的std::for_each显然是错误的。amba 的参数类型应该是Point, 或者 ,Point const&具体取决于您想要执行的操作以及允许您执行的操作。
应该是这样的:
int count = 0;
for_each(PtList.begin(),PtList.end(), [&](Point const & p)
{
cout <<"No. " << ++count << endl;
p();
});
Run Code Online (Sandbox Code Playgroud)
让你的operator()成员函数成为常量。