lambda表达式/匿名函数
当需要一个函数,又不想费力去命令一个函数的情况下使用
语法
[捕捉列表](参数列表)muable(可选)异常属性–>返回类型{
//函数体
}
[caputrue] (parmas) opt ->ret { body; };
int main(){
//lambda表达式就是匿名函数(没有名字的函数)
int c =[](int a,int b)->int{
//函数体
return a+b;
}(1,2);
cout<<c;
}
auto f =[](int a,int b)->int{
//函数体
return a+b;
};
c = f(1,2);
嵌套
//函数式编程,多线程,并对
c =[](int n){
return[n](int x){
return x+n;
}(1);
}(2);
auto f =[](int n){
return[n](int x){
return x+n;
};
};
c = f(1)(2);
mutable
- 修饰成员变量,可以让常成员函数修改成员变量的值
- 只有按值引用,需要修改并需要返回时才需要
int t =10;
auto c =[t]() mutable{ //不加mutable,不能访问外部数据
return ++t; //不影响外面的值
};
匿名函数捕获列表
- 按值捕获
int t = 10;
auto f = [t](){ //捕获的是声明匿名函数时,捕获参数列表的值
cout<<t<<endl;
};
t = 11;
f(); //10
- 按引用捕获
int t =10;
auto c =[&t](){
cout<<t<<endl;
t = 13;
};
t = 11;
c(); //11
cout<<t<<endl; //13
- 按值捕获所有变量
int a = 10;
int b = 20;
auto f = [=](){
cout<<a+b<<endl;
};
f();
- 按引用捕获所有变量
int a = 10;
int b = 20;
auto f = [&](){
cout<<a+b<<endl;
};
f();
- 按值和引用捕获
int a = 10;
int b = 20;
auto f = [a,&b](){
cout<<a+b<<endl;
};
f();
应用
vector<int> v ={1,2,3,4,5};
for_each(v.begin(),v.end(),[](int n){
if(n%2 == 0)
cout<<n<<"是偶数"<<endl;
else
cout<<n<<"是奇数"<<endl;
});