C++ Lambda Expressions with capture section

Introduction

To be able to use the variables in the scope in which the lambda was defined, we need to capture them first.

The capture section marked by [] can capture local variables by copy:

#include <iostream> 

int main() /*from  ww  w . j a va  2  s . co m*/
{ 
    int x = 123; 
    auto mylambda = [x]() { std::cout << "The value of x is: " << x; }; 
    mylambda(); 
} 

Here, we captured the local variable x by value and used it inside our lambda body.

Another way to capture variables is by reference, where we use the [&name] notation.

Example:

#include <iostream> 

int main() /*ww  w  .  j  a v  a 2  s.  co  m*/
{ 
    int x = 123; 
    auto mylambda = [&x]() {std::cout << "The value of x is: " << ++x; }; 
    mylambda(); 
} 

To capture more than one variable, we use the comma operator in the capture list: [var1, var2].

For example, to capture two local variables by value, we use:

#include <iostream> 

int main() //from  w w w .  jav  a2s .com
{ 
    int x = 123; 
    int y = 456; 
     auto mylambda = [x, y]() {std::cout << "X is: " << x << ", y is:   
     " << y; }; 
    mylambda(); 
} 

To capture both local variables by reference, we use:


#include <iostream> 

int main() /*from  w  w w .ja va2 s.c o  m*/
{ 
    int x = 123; 
    int y = 456; 
    auto mylambda = [&x, &y]() {std::cout << "X is: " << ++x << ", y is: "  
    << ++y; }; 
    mylambda(); 
} 



PreviousNext

Related