The lambda expression was introduced in C++11 and convenient way of writing
[ capture_clause ] (parameters) -> return_type
{
lambda_body
}
[]
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.int
.The
capture_clause
is also known as lambda-introducer. Learn more in the offical docs.
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 vectorvoid 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