Lambda comes from the concept of functional programming and is also a feature of modern language programming.
First look at the basic use of lambda:
1 [capture] (params) opt->return {body;}
Where capture is a capturing list (that is, a free variable in a closure):
- [] do not intercept any variables
- [&] intercepts all variables in the outer scope and uses them as references in the body of the function
- [=] intercepts all variables in the outer scope and copies a copy to be used in the body of the function
- [=, &foo] Intercepts all variables in the outer scope and copies a copy to be used in the function body, but uses a reference to the Foo variable
- [bar] Intercept bar variable and copy one copy at function weight without intercepting other variables
- [x, &y] x is passed by value, Y is passed by reference
- [This] intercepts the this pointer in the current class. This option is added by default if you have already used & or =.
The params is the parameter table; Opt is the function option; return is the value type; body is the body of the function.
The type of the lambda expression is referred to as the "closure type" in c++11. We can think of it as a class with operator (). Therefore, you can use Std::function and Std::bind to store their types:
1 std::function<int(int) > f1 = [] (int i) {return i;}; 2 std::function<int(void) > F2 = Std::bind ([] (intreturn A;});
1 intA =0;2 intb =1;3Auto F1 = []{returnA };//error, no external variables captured4Auto F2 = [&]{returna++; };5Auto F3 = [=]{returnA;};6Auto F4 = [=]{returna++; };//Error,a is captured in copy mode and cannot be modified7Auto F5 = [a]{returnA + b; };//error, no capture variable b8Auto F6 = [A, &b]{returnA + (b++); };9Auto F7 = [=, &b]{returnA + (b++); };
Give me a chestnut:
std::vector<int> v = {1234}; int 0 ; For_each (V.begin (), V.end (), [&sum] (int value) { +=" sum: " << sum << endl;
Lambda expressions are relatively simple, so you can easily use lambda after you understand closures.
Lambda function of c++11