Naming a local variable in square brackets [] in Lambda is called capturing the variable . If the variable is not specified in **square brackets []**, it cannot be used in Lambda expressions. Lambda capture variables are passed by value by default.
Such as the following code:
#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>
using namespace std;
int main(int argc, char** argv)
{
// 初始化向量
vector<int> data{1,2,3,4,5,6,7,8,9};
int times = 3;
// 输出原始数据
// 输出
cout << "before transform:\n";
copy(data.begin(),data.end(),ostream_iterator<int>(cout,","));
cout << endl;
// 定义表达
auto op_times = [times](int i){return i * times;};
transform(data.begin(),data.end(),data.begin(),op_times);
// 输出
cout << "after transform times=" << times << endl;
copy(data.begin(),data.end(),ostream_iterator<int>(cout,","));
cout << endl;
// 改变本地变量
times = 5;
transform(data.begin(),data.end(),data.begin(),op_times);
// 输出
cout << "after transform times=" << times << endl;
copy(data.begin(),data.end(),ostream_iterator<int>(cout,","));
cout << endl;
return 0;
}
Program output:
When the value of the local variable times is changed from 3 to 5, the result of calling the transform function is not multiplying each element by 5. This is equivalent to calling the transform function twice. In order to realize that the result of the call changes with the change of the local variable times , the variable needs to be captured by reference.
auto op_times = [×](int i){return i * times;};
The results of the program have reached expectations!
After the lambda expression captures a variable, can the captured variable be changed in the Lambda expression? Take a look at the following code:
#include <iostream>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>
using namespace std;
int main(int argc, char** argv)
{
int x{0};
auto test_func = [x](int y){
// 改变参数的值
x = 1;
y = 2;
return x + y;
};
int local{0};
cout <<"after call test_func:"<< test_func(local) <<",x = " << x <<",local=" << local << endl;
return 0;
}
The results of the compilation are as follows:
This shows that the capture of variables in the value transfer mode cannot be modified in the Lambda expression!