Lambda expressions were introduced in C++11 to allow the definition of small, anonymous functions directly at the point of use. One of the most important features of lambdas is the capture clause, which controls how variables from the surrounding scope are accessed inside the lambda body.
Before exploring the Lambda Capture clauses make sure you are familiar with Lambda Expressions in C++.
Lambda Capture Clauses in C++
The general syntax for a lambda expression is as follows:
[ capture_clause ] (parameters) -> return-type
{
definition of method
}
- The capture clause is specified inside square brackets []
- It determines how external variables are accessed inside the lambda
There are three ways to capture external variables using the Lambda Capture clauses
- Capture by reference
- Capture by value
- Capture by both reference and value (mixed capture)
Note: A lambda with an empty capture clause [ ] can only access variables which are local to it.
Examples of Lambda Captures
Example 1: Capture Values by Reference
In the following example, we will see how we can capture an external variable by reference so that the lambda function can modify the original variable.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> vec