08. C++ Lambda expression

Posted by Yulai Blog on November 8, 2015
  1. Lambda expression
 [capture](parameters) -> return_type { function_body } 
1
2
3
* An example lambda function is defined as follows:

* 
 [](int x, int y) -> int { return x + y; } 
1
2
* C++11 also supports closures. Closures are defined between square brackets `[` and `]` in the declaration of lambda expression. 
* The mechanism allows these variables to be captured by value or by reference. The following table demonstrates this:
   

[]        //no variables defined. Attempting to use any external variables in the lambda is an error.
[x, &y]   //x is captured by value, y is captured by reference
[&]       //any external variable is implicitly captured by reference if used
[=]       //any external variable is implicitly captured by value if used
[&, x]    //x is explicitly captured by value. Other variables will be captured by reference
[=, &z]   //z is explicitly captured by reference. Other variables will be captured by value
#include <iostream>
#include <vector>
#include <algorithm>

void c11_lambda()
{
    std::vector<int> some_list{1, 2, 3, 4, 5};
    
    std::for_each (some_list.begin (), some_list.end (), [](int x) {std::cout << x << std::endl;});
    
    int sum_1 (0);
    int sum_2 (0);
    
    // error: 'sum_1' is not captured
    // error: 'sum_2' is not captured
    // std::for_each(some_list.begin(), some_list.end(), [](int x){sum_1 += x; sum_2 += x;});
    std::for_each (some_list.begin (), some_list.end (), [&](int x) {sum_1 += x; sum_2 += x;});
    std::cout << "sum_1 = " << sum_1 << " sum_2 = " << sum_2 << std::endl;
    
    // error: assignment of read-only variable 'sum_1'
    // std::for_each(some_list.begin(), some_list.end(), [=](int x){sum_1 += x; sum_2 += x;});
    
    sum_1 = sum_2 = 0;
    // error: assignment of read-only variable 'sum_2'
    // std::for_each(some_list.begin(), some_list.end(), [&, sum_2](int x){sum_1 += x; sum_2 += x;});
    std::for_each (some_list.begin (), some_list.end (), [&, sum_2](int x) {sum_1 += x;});
    std::cout << "sum_1 = " << sum_1 << " sum_2 = " << sum_2 << std::endl;
    
    sum_1 = sum_2 = 0;
    // error: assignment of read-only variable 'sum_1'
    // std::for_each(some_list.begin(), some_list.end(), [=, &sum_2](int x){sum_1 += x; sum_2 += x;});
    std::for_each (some_list.begin (), some_list.end (), [ =, &sum_2](int x){sum_2 += x;});
    std::cout << "sum_1 = " << sum_1 << " sum_2 = " << sum_2 << std::endl;
}
1
2
3
  sum_1 = 15 sum_2 = 15
  sum_1 = 15 sum_2 = 0
  sum_1 = 0 sum_2 = 15