0. lambda emerged since c++11, lambda expression/function is an unnamed function object capable of capturing variables in scope.
A lambda function is a function that you can write inline in your source code (usually to pass in to another function, similar to the idea of a function pointer).
1. syntax of a lambda expression
[
captures ]
<tparams>(optional)(c++20) (
params )
specifiers exception attr ->
ret requires(optional)(c++20){
body }
[
captures ]
(
params )
->
ret {
body }
[
captures ]
(
params )
{
body }
[
captures ]
{
body }
2. Examples:
[](){}; // barebone lambda, [] is the capture list, ()is the argument list, {} is the function body
[](){}(); // immediately execute a lambda or call the lambda function
auto pr = [](int& n){n = n+1; std::cout << " " << n;}; // define a lambda function, and assign it to the pr
#include <algorithm> // std::for_each()
std::for_each(v.begin(), v.end(), pr); // caller of the lambda expression
std::for_each(v.begin(), v.end(), [](int &n){ n++; std::cout << " " << n; }); // the same lambda function caller
3. About capture list
[] | Capture nothing |
[&] | Capture any reference variable by reference |
[=] | Capture any reference variable by making a copy |
[=, &foo] | Capture any referenced variable by making a copy, but capture variable foo by reference |
[bar] | |
[this] |
int x = 4;
auto y = [&r = x, x = x+1]()->int{ r += 2; return x+2;}(); //::x will be 6, y will be 7;
or
auto y = [&r = x, x = x+1]()->int{ r += 2; return x+2;}; // it is not excuted now
y(); // it is executed. ::x is 6