Or assume another simple sample
void TestFunctions::simpleLambda() { bool sensitive = true; std::vector<int> v = std::vector<int>({1,33,3,4,5,6,7}); sort(v.begin(),v.end(), [sensitive](int x, int y) { printf("\n%i\n", x < y); return sensitive ? x < y : abs(x) < abs(y); }); printf("sorted"); for_each(v.begin(), v.end(), [](int x) { printf("x - %i;", x); } ); } will generate next
0
1
0
1
0
1
0
1
0
1
0 sortedx - 1;x - 3;x - 4;x - 5;x - 6;x - 7;x - 33;
[] - this is capture list or lambda introducer: if lambdas require no access to their local environment we can use it.
Quote from book:
The first character of a lambda expression is always [. A lambda introducer can take various forms:
• []: an empty capture list. This implies that no local names from the surrounding context can be used in the lambda body. For such lambda expressions, data is obtained from arguments or from nonlocal variables.
• [&]: implicitly capture by reference. All local names can be used. All local variables are accessed by reference.
• [=]: implicitly capture by value. All local names can be used. All names refer to copies of the local variables taken at the point of call of the lambda expression.
• [capture-list]: explicit capture; the capture-list is the list of names of local variables to be captured (i.e., stored in the object) by reference or by value. Variables with names preceded by & are captured by reference. Other variables are captured by value. A capture list can also contain this and names followed by ... as elements.
• [&, capture-list]: implicitly capture by reference all local variables with names not men- tioned in the list. The capture list can contain this. Listed names cannot be preceded by &. Variables named in the capture list are captured by value.
• [=, capture-list]: implicitly capture by value all local variables with names not mentioned in the list. The capture list cannot contain this. The listed names must be preceded by &. Vari- ables named in the capture list are captured by reference.
Note that a local name preceded by & is always captured by reference and a local name not pre- ceded by & is always captured by value. Only capture by reference allows modification of variables in the calling environment.
Additional
Lambda expression format
