How it works...

In the first example, the lambda function just gets an integer as input and prints it. Note that the code is concise and readable. Lambda can capture the variables in scope by reference, &, or by value, =

The output of the second program is as follows:

In the second example, the lambda captures the variable prefix by reference, making it visible to the lambda. Here, we captured the prefix variable by reference, but we might have captured any of the following:

There are cases where we have to be explicit about the type to return, as in this case:

[](int x) -> std::vector<int>{
if (x%2)
return {1, 2};
else
return {3, 4};
});

The -> std::vector<int> operator, called trailing return type, tells the compiler that this lambda will return a vector of integers.