lambda函数,即匿名函数
[ ] (int x) { return x%3==0; }
其中 []表示匿名函数,x表示形参
#include <iostream>
using namespace std;
void main()
{
auto fmod3=[](int x){return x%3==0;};
cout<<fmod3(3)<<endl;
getchar();
}
其中 fmod3是函数指针。
如果指定返回值
[ ] (int x)->bool { return x%3==0; }
lambda函数可以变量截取
- [] 不截取任何变量
- [&] 截取外部作用域中所有变量,并作为引用在函数体中使用
- [=] 截取外部作用域中所有变量,并拷贝一份在函数体中使用
- [=, &foo] 截取外部作用域中所有变量,并拷贝一份在函数体中使用,但是对foo变量使用引用
- [bar] 截取bar变量并且拷贝一份在函数体重使用,同时不截取其他变量
- [this] 截取当前类中的this指针。如果已经使用了&或者=就默认添加此选项。
(来源:http://www.cnblogs.com/lidabo/p/3908663.html)
示例(C++ primers plus edition 6)
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <ctime>
const long Size=390000L;
int main()
{
using namespace std;
std::vector<int> numbers(Size);
std::srand(std::time(0));
std::generate(numbers.begin(),numbers.end(),std::rand);
cout<<"Sample size= "<<Size<<'\n';
//using lambdas
int count3=std::count_if(numbers.begin(),numbers.end(),
[](int x){return x%3==0;});
cout<<"Count of numbers divisible by 3: "<<count3<<'\n';
int count13=0;
std::for_each(numbers.begin(),numbers.end(),
[&count13](int x){count13 += x%13==0;});
cout<<"Count of numbers divisible by 13: "<<count13<<'\n';
//using a single lambda
count3=count13=0;
std::for_each(numbers.begin(),numbers.end(),
[&](int x){ count3+=x%3==0; count13+=x%13==0;});
cout<<"Count of numbers divisible by 3: "<<count3<<'\n';
cout<<"Count of numbers divisible by 13: "<<count13<<'\n';
return 0;
}