Open In App

How to use C++ Lambdas with Capture Clauses?

In C++, lambda expressions provide a convenient way to create one-liner functions. One of the key features of lambdas is their ability to capture variables from their surrounding scope by using capture clauses. This allows lambdas to access and modify variables from the outer scope, even after the lambda itself has been created. In this article, we will learn about what are lambdas with capture clauses in C++.

C++ Lambdas with Capture Clauses

Capture clauses are specified within the square brackets after the lambda expression's parameter list. They also define how the variables from the surrounding scope are being captured by the lambda.

Following is the syntax for lambda expressions with capture clauses:

Syntax

[capture-list] (parameters) -> return-type {
// lambda body
}

There are mainly two types of capture clauses in lambda expressions :

C++ Program to Capture a Variable by Value using Lamda

In the following example , we will capture a variable x by value in the lambda expression. Later the value of the variable is modified but it is not reflected inside the lambda function because the variable was captured using the value.

// C++ program to capture a value by value in lambda
// expression
#include <iostream>
using namespace std;

int main()
{
    int x = 50;
    // capture x by value
    auto lambda
        = [x]() { cout << "Inside lambda: " << x << endl; };
    // modify the value of x outside lambda expression
    x = 100;
    // Call the lambda function to print its captured value
    // of x
    lambda();

    // Print the original value of x
    cout << "Outside lambda: " << x << endl;
    return 0;
}

Output
Inside lambda: 50
Outside lambda: 100

Time Complexity: O(1)
Auxiliary Space: O(1)

C++ Program to Capture a Variable by Reference using Lambda

In the following example , we will capture a variable x by reference in the lambda expression. Later the value of the variable is modified and the modified value will be used in the lambda function as the variable was passed by reference.

// C++ program to capture a value by reference in lambda
// expression
#include <iostream>
using namespace std;

int main()
{
    int x = 50;
    // capture x by reference
    auto lambda = [&x]() {
        cout << "Inside lambda: " << x << endl;
    };
    // modify the value of x outside lambda expression
    x = 100;
    // Call the lambda function to print its captured value
    // of x
    lambda();

    // Print the original value of x
    cout << "Outside lambda: " << x << endl;
    return 0;
}

Output
Inside lambda: 100
Outside lambda: 100



Article Tags :