c ++ 11: use of lambda expressions

The general form of lambda expressions:

 [capture list] (parameter list) -> return type{function body}; 

Wherein, capture list (capture list) is a list (usually empty) a lambda where local variables are defined;

return type, parameter list, and as with any normal function body functions respectively return type, and the body of the function parameter list.

However, different from the ordinary function, lambda must be set back to the end of the specified return type.

 

In addition, I can ignore the parameter list and return type, but must always contain a list and capture function body:

auto f = [] { return 42 }

In this example, we define a callable objects F, no arguments, returns a value of 42;

 

Called: consistent with the normal function;

cout << f() << endl;

Ignoring the case of the return type, lambda inferred return type code in accordance with the function thereof; If the function thereof is only a return statement, return type of the return type inferred from the expression. Otherwise, the return type of void.

 

Conditions of Use:

"Reference capture is sometimes necessary, for example, we might want biggies function accepts a reference to an ostream, which is used to output data, and accepts a character as the delimiter:."

void the biggies (Vector < String > & words, 
                  Vector < String > :: size_type SZ, 
                  the ostream & OS = COUT, char C = '  ' ) 
{ 
     // print count statements to print to OS 
    the for_each (words.begin (), words.end (), 
                  [ & OS, C] ( const  String & S) S {OS << << C;});           
}

We can not copy the ostream, so the only method is to capture the capture os its reference (or a pointer to the os).

Note: When capturing a reference variable, the variable must ensure execution when lambda is there .

 

In general, we should minimize the amount of data captured, to avoid potential problems caused by the capture. And, if possible, should be avoided capture pointer or reference.

Guess you like

Origin www.cnblogs.com/2018shawn/p/11361053.html