cpp-lambda表达式

Lambda的语法如下:
[函数对象参数](操作符重载函数参数)->返回值类型{函数体}

vector<int> iv{5, 4, 3, 2, 1};
int a = 2, b = 1;

for_each(iv.begin(), iv.end(), [b](int &x){cout<<(x + b)<<endl;}); // (1)
for_each(iv.begin(), iv.end(), [=](int &x){x *= (a + b);}); // (2)
for_each(iv.begin(), iv.end(), [&](int &x)->int{return x * (a + b);});// (3)
  • []内的参数指的是Lambda表达式可以取得的全局变量。
    (1)函数中的b就是指函数可以得到在Lambda表达式外的全局变量,如果在[]中传入=或者&的话,即是可以取得所有的外部变量,如(2)和(3)Lambda表达式,& 表示传引用
  • ()内的参数是每次调用函数时传入的参数。
  • ->后加上的是Lambda表达式返回值的类型,如(3)中返回了一个int类型的变量
& captures by reference
= captures by value

int x = 1;
auto valueLambda = [=]() { cout << x << endl; };
auto refLambda = [&]() { cout << x << endl; };
x = 13;
valueLambda();
refLambda();

This code will print
1
13

[&epsilon] capture by reference
[&] captures all variables used in the lambda by reference
[=] captures all variables used in the lambda by value
[&, epsilon] captures variables like with [&], but epsilon by value
[=, &epsilon] captures variables like with [=], but epsilon by reference