Open In App

How to Capture std::vector in Lambda Function?

Last Updated : 31 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, lambda functions allow users to define an inline function anywhere in the program. They are also able to capture the objects from outside its definition. In this article, we will look at how to capture a std::vector object in lambda functions in C++.

Capture std::vector in Lambda Function

To capture the std::vector container object that is present outside of the lambda function definition, we can use the capture clause of the lambda expression. The capture clause allows both capture by value and capture by reference method.

Capture by Value

[vector_name] (args){
    // code
}

Capture by Reference

[&vector_name] (args) {
    // code
}

C++ Program to Capture std::vector in Lambda Function

C++




// C++ program to capture std::vector in a lambda function
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
  
int main()
{
    vector<int> vec = { 1, 2, 3, 4, 5 };
  
    // Lambda function capturing vector by reference
    auto printVector = [&vec]() mutable {
        for (auto elem : vec) {
            cout << elem << " ";
        }
        cout << endl;
    };
  
    // modifying vector by capturing using value
    auto addVectorV = [vec]() mutable{
        for (auto& elem : vec) {
            elem = elem + 1;
        }
    };
  
    // modifying vector by capturing using reference
    auto addVectorR = [&vec]() {
        for (auto& elem : vec) {
            elem = elem + 1;
        }
    };
  
    addVectorV();
    cout << "Original Vector after calling addVectorV: ";
    printVector();
  
    addVectorR();
    cout << "Original Vector after calling addVectorR: ";
    printVector();
  
    return 0;
}


Output

Original Vector after calling addVectorV: 1 2 3 4 5 
Original Vector after calling addVectorR: 2 3 4 5 6 


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads