[C++11] Lambda表达式
Lambda表达式是一个匿名函数
。基本语法如下:
[capture list] (parameter list) -> return type {function body}
同Python的Lambda表达式不同的是,C++11的Lambda多了capture list
,用于指定作用域(C++为块作用域)内的变量的传递方式,是传值还是传引用,而Python默认为不可变对象传值,可变对象传引用,类似lambda x: x**2。下面介绍capture list的用法:
- [] 没有定义变量,如果在函数体内使用未定义的变量会导致错误。
- [&] 所有变量都以传引用的方式使用
- [=]所有变量都已传值方式使用
- [&,x] x使用传值,其他都使用传引用
- [=, &z] z使用传引用,其他都使用传值
- [x , &y] x使用传值,y使用传引用
[image:477183C9-6BB8-455C-9DB2-928824C6A29C-57121-00008A3D53C478E4/4106E0D7-9541-47E2-8BB4-169B400D97DB.png]
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> tmp;
tmp.push_back(1);
tmp.push_back(2);
// 无函数对象参数,输出1,2
{
for_each(tmp.begin(), tmp.end(), [](int v){cout << v << endl;});
}
// a传值,输出11,12,10
{
int a = 10;
for_each(tmp.begin(), tmp.end(), [=](int v){cout << v+a << endl;});
cout << a << endl;
}
// a传引用,输出11,13,12
{
int a = 10;
for_each(tmp.begin(), tmp.end(), [&](int v){cout << v+a << endl;a++;});
cout << a << endl;
}
// 同上
{
int a = 10;
for_each(tmp.begin(), tmp.end(), [&a](int v){cout << v+a << endl;a++;});
cout << a << endl;
}
// a传值,b传应用,并且如果对a++,会报错,输出11,12,22
{
int a = 10;
int b = 20;
for_each(tmp.begin(), tmp.end(), [=, &b](int v){cout << v+a << endl;b++;});
cout << b << endl;
}
// 对函数参数进行传引用,输出2,3
{
for_each(tmp.begin(), tmp.end(), [](int &v){v++;});
for_each(tmp.begin(), tmp.end(), [](int v){cout << v << endl;});
}
// 空lambda
{
[](){}();
[]{}();
}
}