Open In App

How to Capture Pairs in Lambda Expression in C++?

Last Updated : 07 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, lambda expressions provide an easy way to define anonymous functions inline. They also allow these inline functions to capture some variables from the surrounding scope.

In this article, we will learn how to capture pairs in lambda functions in C++

Capture Pairs in Lambda Expressions in C++

We can capture the variables from the surrounding scope of the lambda expression and then use them inside that function. The general syntax for a lambda expression is as follows:

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

To capture pairs, we mention the name of the pair in the square brackets. If we only use the name, then the pair will be captured by value. If we use the & operator with the name, the pair will be captured by reference.

C++ Program to Capture Pairs in Lamda Expressions

C++




// C++ program to demonstrate how to capture pairs in lambda
// expression
#include <iostream>
#include <utility>
  
using namespace std;
  
int main()
{
  
    // initialize some pairs
    pair<int, string> pair1 = make_pair(100, "geeks");
    pair<int, string> pair2 = make_pair(200, "for");
    pair<int, string> pair3 = make_pair(300, "geeks");
  
    // capture pairs in lambda function
    auto lambda = [pair1, pair2, pair3]() {
        cout << pair1.first << " " << pair1.second << endl;
        cout << pair2.first << " " << pair2.second << endl;
        cout << pair3.first << " " << pair3.second << endl;
    };
  
    // Call the lambda function to print the pairs
    lambda();
  
    return 0;
}


Output

100 geeks
200 for
300 geeks

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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads