16.5. Lambda Expressions

As you’ve seen in this chapter, many algorithms can receive function pointers or function objects as parameters. Before you can pass a function pointer or function object to an algorithm, the corresponding function or class must have been declared.

Image

C++11’s Lambda expressions (or lambda functions) enable you to define anonymous function objects where they’re passed to a function. They’re defined locally inside functions and can “capture” (by value or by reference) the local variables of the enclosing function then manipulate these variables in the lambda’s body. Figure 16.16 demonstrates a simple lambda expression example that doubles the value of each element in an int array.


 1   // Fig. 16.16: fig16_16.cpp
 2   // Lambda expressions.
 3   #include <iostream>
 4   #include <array>
 5   #include <algorithm>
 6   using namespace std;
 7
 8   int main()
 9   {
10      const size_t SIZE = 4; // size of array values
11      array< int, SIZE >  values = { 1, 2, 3, 4 }; // initialize values
12
13      // output each element multiplied by two
14      for_each( values.cbegin(), values.cend(),
15         []( int i ) { cout << i * 2 << endl; } );
16
17      int sum = 0; // initialize sum to zero
18
19      // add each element to sum
20      for_each( values.cbegin(), values.cend(),
21         [ &sum ]( int i ) { sum += i; } );
22
23      cout << "sum is " << sum << endl; // output sum
24   } // end main


2
4
6
8
sum is 10


Fig. 16.16. Lambda expressions.

Lines 10 and 11 declare and initialize a small array of ints named values. Lines 14–15 call the for_each algorithm on the elements of values. The third argument (line 15) to for_each is a lambda expression. Lambdas begin with lambda introducer ([]), followed by a parameter list and function body. Return types can be inferred automatically if the body is a single statement of the form return expression;—otherwise, the return type is void by default or you can explicitly use a trailing return type (introduced in Section 6.18). The compiler converts the lambda expression into a function object. The lambda expression in line 15 receives an int, multiplies it by 2 and displays the result. The for_each algorithm passes each element of the array to the lambda.

The second call to the for_each algorithm (lines 20–21) calculates the sum of the array elements. The lambda introducer [&sum] indicates that this lambda expression captures the local variable sum by reference (note the use of the ampersand), so that the lambda can modify sum’s value. Without the ampersand, sum would be captured by value and the local variable outside the lambda expression would not be updated. The for_each algorithm passes each element of values to the lambda, which adds the value to the sum. Line 23 then displays the value of sum.

You can assign lambda expressions to variables, which can then be used to invoke the lambda expression or pass it to other functions. For example, you can assign the lambda expression in line 15 to a variable as follows:

auto myLambda = []( int i ) { cout << i * 2 << endl; };

You can then use the variable name as a function name to invoke the lambda as in:

myLambda( 10 ); // outputs 20

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.226.84