C++中的Lambda表达式
基本表达格式:
[captureList] (parameterList) -> returnType {function body}
一、捕获(capture)
1、值捕获(capture by value)
值捕获的变量在Lambda表达式定义时就已经确定
例子:
# include <iostream>
using namespace std;
int main(){
int x = 5;
auto f = [x] (int y) -> int {return x+y;};
x = 50;
cout << f(5) << endl;
return 0;
}
结果
10
2、引用捕获(capture by reference)
在Lambda函数定义时,捕获变量前面加上&,表示捕获对应变量的内存地址,这样捕获变量的值在函数调用时才会确定
# include <iostream>
using namespace std;
int main(){
int x = 5;
auto f = [&x] (int y) -> int {return x+y;};
x = 50;
cout << f(5) << endl;
return 0;
}
结果
55
3、隐式捕获(implict capture)
在捕获变量中不使用具体的变量名,而只使用=或者&,表示捕获函数所需的所有外部变量的值或引用,这样可以避免遗漏。
只使用=
# include <iostream>
using namespace std;
int main(){
int x = 5;
int y = 10;
auto f = [=] (int z) -> int {return x+y+z;};
x = 50;
y = 100;
cout << "f(5)=" << f(5) << endl;
return 0;
}
结果
f(5)=20
只使用&
# include <iostream>
using namespace std;
int main(){
int x = 5;
int y = 10;
auto f = [&] (int z) -> int {return x+y+z;};
x = 50;
y = 100;
cout << "f(5)=" << f(5) << endl;
return 0;
}
结果
f(5)=155
注意:不能同时使用=和&,因为这样会造成冲突,导致函数无法理解到底是捕获值还是捕获引用,编译也会报错