function defines a callable entity
Lamda equivalent to closures, anonymous functions, block in OC
The following is a demo of the use of a simple answer
function <int (int, int) > myfunc;//Enter parameter is Int,int, the out parameter is int
MyFunc = [] (int x,int y)->int{
return x + y;
};//Assigning a value to Func
cout << MyFunc (Ten) << endl;//call
#include"stdafx.h"#include<iostream>#include<map>#include<functional>using namespacestd;//Common FunctionsintAddintIintj) {returni +J;}//lambda expressionAuto mod = [] (intIintj) {returnIJ;};//function Object classstructdivide{int operator() (intDenominator,intdivisor) { returnDenominator/Divisor; }};///////////////////////////Submain//////////////////////////////////intMainintargcChar*argv[]) { //Restricted mapmap<Char,int(*) (int,int) >Binops_limit; Binops_limit.insert ({'+', add}); Binops_limit.insert ({'%', mod}); //Error 1 C2664: "Void Std::_tree<std::_tmap_traits<_kty,_ty,_pr,_alloc,false>>::insert (Std::initi ALIZER_LIST<STD::p air<const _kty,_ty>>) ": cannot convert parameter 1 from" Initializer-list "to" std::p air<const _kty,_ty > && "//binops_limit.insert ({'% ', Divide ()}); //a more flexible mapmap<Char, function<int(int,int) >> Binops = { { '+', add}, {'-', minus<int>() }, { '*', [](intIintj) {returnIJ;} }, { '/', Divide ()}, {'%', mod},}; cout<< binops['+'](Ten,5) <<Endl; cout<< binops['-'](Ten,5) <<Endl; cout<< binops['*'](Ten,5) <<Endl; cout<< binops['/'](Ten,5) <<Endl; cout<< binops['%'](Ten,5) <<Endl; function<int(int,int) >MyFunc; MyFunc= [](intXintY)int{ returnX +y; }; cout<< MyFunc (Ten, -) <<Endl; System ("Pause"); return 0;}
Ps:lamda Methods for capturing parameters
in the body of a lambda expression, it is not possible to access external variables, and if you want to use variables defined outside the body of the function, you need to "capture" them.
Capture, [=], [=,&], [&], [This]
[]: Empty capture list, where a lambda expression cannot use a variable in a function
[=]: Value capture, that is, a lambda expression can be copied to access the value of a variable in a function
[&]: Reference capture, that is, the variable in the function in which the lambda expression is used is a reference
When we do not want to capture all the variables at the time of capture, we can use the following side
[=, &foo] is captured by a copy of the variable, but is captured with a reference to the Foo variable
[Bar] By copying the capture, do not copy other
[This] captures the corresponding member of this pointer
C + + function &n Lamda expression simple to use