Open In App

How to Pass an Array into a Lambda Function in C++?

Last Updated : 06 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, a lambda function, also known as a lambda expression, is a way of defining an anonymous function object right at the location where it is invoked or passed as an argument to a function. In this article, we will learn how to pass an array into a lambda function in C++.

Passing an Array into a Lambda Function in C++

To pass an array into a lambda function in C++, we can simply pass the array as an argument to the lambda function. Inside the lambda function, we can access the elements of the array just like we would in a regular function in C++.

Note: Remember to pass the size of the array as a parameter too.

C++ Program for Passing an Array into a Lambda Function

C++




// C++ Program to illustrate how to pass an array into a
// lambda function
#include <iostream>
using namespace std;
  
// Define a lambda function that takes an array as a
// parameter
auto printArray = [](int arr[], int size) {
    for (int i = 0; i < size; ++i) {
        cout << arr[i] << " ";
    }
    cout << endl;
};
  
int main()
{
    // Creating an array
    int arr[5] = { 1, 2, 3, 4, 5 };
  
    // Passing the array into the lambda function
    printArray(arr, 5);
  
    return 0;
}


Output

1 2 3 4 5 

Time complexity: O(N), where N is the number of elements in the array.
Auxiliary Space: O(1)

If the lambda expression is in the same scope as that of the array, we can also use the capture clause of the lambda expression to accesss the array inside it.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads