Lambda expressions in C++

The lambda expression was introduced in C++11 and convenient way of writing anonymous functionsinline functions that do not need to be named.

Syntax

[ capture_clause ] (parameters) -> return_type  
{   
   lambda_body  
}
  • capture_clause: Specifies which variables are capturedaccessed from the surrounding scope, and whether the capture is by value or by reference. In capture_clause, [] is the empty clause, which means that the lambda expression accesses no variables in the enclosing scope. [&] means all variables that you refer to are captured by reference. [=] means they are captured by value, e.g., [a, &b] captures a by value and b by reference.
  • parameters: These are optional to the function, just like regular parameters in C++ functions.
  • return_type: Optional return type, e.g., int.
  • lambda_body: Body of the lambda function.

The capture_clause is also known as lambda-introducer. Learn more in the offical docs.

Code

In this example, we sort a vector descendingly. By default, the sort() function sorts ascendingly. However, we can pass a lambda expression as the third argument to the sort() function to have our own custom way of comparing vector elements. The lambda expression has an empty capture clause that takes two parameters (a and b) and returns a boolean.

#include <iostream>
#include <vector>
#include <stdlib.h> /* srand, rand */
#include <algorithm>
using namespace std;
// Helper function to print a vector
void printVector(vector<int> V) {
for (int i=0; i < V.size(); i++)
cout << V[i] << " ";
cout << endl;
}
int main() {
vector<int> V {3, 2, 5, 7, 1, 4, 6};
cout << "Before:\t";
printVector(V);
// The third argument to the sort function is a lambda expression
// that has an empty capture clause, has two parameters a and b,
// and returns a boolean. The lambda body is just a > b in order
// to sort the values descendingly.
sort(V.begin(), V.end(), [](const int& a, const int& b) -> bool
{
return a > b;
});
cout << "After:\t";
printVector(V);
}

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved