Lambda expressions were introduced in C++11 and provide a concise way to create anonymous function objects.
The basic syntax of a lambda expression is:
[capture-list](parameter-list) -> return-type { function-body }
Where:
capture-list
: Specifies which variables from the surrounding scope are accessibleparameter-list
: Similar to function parametersreturn-type
: Optional, compiler can often deduce itfunction-body
: The code to executeauto add = [](int a, int b) { return a + b; };
std::cout << add(5, 3); // Outputs: 8
int multiplier = 5;
auto multiply = [multiplier](int x) { return x * multiplier; };
std::cout << multiply(3); // Outputs: 15
By default, variables captured by value cannot be modified. Use the mutable
keyword to allow modification:
int counter = 0;
auto increment = [counter]() mutable { return ++counter; };
std::cout << increment(); // Outputs: 1
std::cout << counter; // Outputs: 0 (original not modified)
Lambda expressions are commonly used with algorithms from the standard library, such as std::sort
, std::for_each
, and std::transform
.