C++ lambda expression
A lambda expression is a small function you can write directly inside your code.
Use a lambda when you need a short function for one local task.
Basic shape:
Parts:
[]: capture list, controls which outside variables the lambda can use(): function arguments{}: function body
Simple example
Output:
The lambda is stored in the variable say_hello.
Then we call it like a normal function:
Lambda with arguments
A lambda can receive arguments like a normal function.
Output:
Here:
means: create a small function that receives two int values and returns their
sum.
Pass a lambda to a function
Lambdas are often passed to other functions.
Example with std::sort:
Output:
The lambda tells std::sort how to compare two numbers.
Scope and capture
A lambda has its own scope.
Variables created inside the lambda are local to the lambda:
The variable value exists only inside the lambda body.
Outside variables are not available unless you capture them.
This does not compile:
To use x, capture it.
Capture by value
Capture by value copies the outside variable into the lambda.
Output:
The lambda copied x when it was created. Later changes to the outside x do
not change the lambda copy.
Capture by reference
Capture by reference lets the lambda use the original outside variable.
Output:
The lambda uses the same x from the outer scope.
Modify captured values
By default, a value captured by copy is read-only inside the lambda.
This does not compile:
Use mutable if you want to modify the lambda copy:
Output:
mutable changes only the lambda copy. The outside x is still 5.
Capture everything
C++ also supports short capture forms.
Capture all used outside variables by value:
Capture all used outside variables by reference:
These are convenient, but for beginner code it is usually clearer to capture only what you need:
Here:
xis captured by valuetotalis captured by reference
Key points
- A lambda is a small local function.
- Use
autoto store a lambda. - Put arguments in
(). - Use
[]to capture outside variables. [x]capturesxby value.[&x]capturesxby reference.- Use
mutableonly when you need to modify a captured copy. - Prefer explicit captures when learning.