lambda函数的表达式:
[capture](param) mutable ->return-type {body}
capture可以捕捉外部变量的各种形式
[] 不截取任何变量
[&} 截取外部作用域中所有变量,并作为引用在函数体中使用
[=] 截取外部作用域中所有变量,并拷贝一份在函数体中使用
[=, &x] 截取外部作用域中所有变量,并拷贝一份在函数体中使用,但是对x变量使用引用
[bar] 截取bar变量并且拷贝一份在函数体重使用,同时不截取其他变量
[this] 截取当前类中的this指针。如果已经使用了&或者=就默认添加此选项。
这里以[=,&x]作为例子,可以看到a是拷贝,而b是使用的是引用。
可能有些人会想[=,&x]可以的话那么[&,=x]是不是也行(报错)
是要这样[&,x]才行(=可以忽略)
int a=1,b=2;
cout<<&a<<" "<<&b<<endl;
auto func = [=,&b](){
cout<<&a<<" "<<&b<<endl;
};
func();
/*
output:
0x73fe1c 0x73fe18
0x73fe08 0x73fe18
*/
int a=1,b=2;
cout<<&a<<" "<<&b<<endl;
auto func = [&,b](){
cout<<&a<<" "<<&b<<endl;
};
func();
/*
output:
0x73fe1c 0x73fe18
0x73fe1c 0x73fe00
*/
lambda的使用技巧
正常数组的自定义排序可以这样使用,其中在类中使用自定义排序时,cmp()函数需要加上static变成静态函数,不加上static是会报错的。(error: reference to non-static member function must be call)
因为类的成员函数默认是会加上*this指针的,那么会变成cmp(auto this,vector&a,vector&b),因此会与sort的自定义排序需要的参数不一致。
class Solution {
public:
static bool cmp(vector<int>&a,vector<int>&b)const{
return a[1]>b[1];
}
int maximumUnits(vector<vector<int>>& boxTypes, int truckSize) {
sort(boxTypes.begin(),boxTypes.end(),cmp);
}
};
使用lambda来自定义排序就比较方便了
class Solution {
public:
int maximumUnits(vector<vector<int>>& boxTypes, int truckSize) {
sort(boxTypes.begin(),boxTypes.end(),[](vector<int>&a,vector<int>&b){
return a[1]>b[1];
});
}
};