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;
}