C++, lambda function/expression


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





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



int x = 4;

auto y = [&r = x, x = x+1]()->int{ r += 2; return x+2;}(); //::x will be 6, y will be 7;


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