Definitely my favorite!
The definition:
[capture clause] (parameters) mutable ->returntype
{ lambda body...}
[] : Capture nothing
[x] : Capture by value
[&x] : Capture by reference
[&] : Capture all (all variables in lambda body scope) by reference
[=] : Capture all (all variables in lambda body scope) by value
[&, x]: Capture all (all variables in lambda body scope) but x by reference
[=, &x] : Capture all (all variables in lambda body scope) but x by value
[x, &y] : Capture x by value, y by reference
If 'mutable' is specified, it is allowed to mutate the values that have been captured by value.
1) Capture nothing, return void.
vector<int> v = {1, 2, 3};
for_each(v.begin(), v.end(), [] (int val) {
cout << val << " ";
});
2) Capture by value, return void.
int y = 4;
vector<int> v = {1, 2, 3};
for_each(v.begin(), v.end(), [y] (int val) {
cout << val * y<< " ";
});
cout << "\n" << y << "\n";
3) Capture by reference, return void.
int y = 1;
vector<int> v = {1, 2, 3};
for_each(v.begin(), v.end(), [&y] (int val) {
y *= val;
});
cout << y << "\n";
4) Capture all by reference, return void.
int y = 1;
int z = 1;
vector<int> v = {1, 2, 3};
for_each(v.begin(), v.end(), [&] (int val) {
y *= val;
z *= y;
});
cout << y << "\n" << z << "\n";
5) Capture all by value, return void (invalid case).
int y = 1;
int z = 1;
vector<int> v = {1, 2, 3};
for_each(v.begin(), v.end(), [=] (int val) {
y *= val;
z *= y;
cout << y << " " << z << " ";
});
/home/lpadmin/c++/src/lambda.cpp:12:39: error: assignment of read-only variable ‘y’
/home/lpadmin/c++/src/lambda.cpp:13:39: error: assignment of read-only variable ‘z’
valid case:
int y = 1;
int z = 1;
vector<int> v = {1, 2, 3};
for_each(v.begin(), v.end(), [=] (int val) mutable {
y *= val;
z *= y;
cout << y << " " << z << " ";
});
cout << "\n" << y << "\n" << z << "\n";
6) Capture nothing, return int (like transform).
vector<int> v = {1, 2, 3};
auto f = [](int val)->int {
return val * 2;
};
for(auto &i: v)
{
i = f(i);
}
7) By default, Lambdas have "no default constructor and assignment operator are defined"