Lambda Expressions in C++
A lambda is an anonymous function object written inline: [capture](params) { body }. The capture list controls what surrounding variables the body may use — [=] copies them, [&] references them, [x, &y] mixes per-variable — while the parameter list and body work exactly like a normal function.
Lambdas are the glue of modern C++: predicates for STL algorithms (sort with custom order), callbacks, and tiny adapters that would otherwise need whole named functions. Generic lambdas (auto params, C++14) double as terse templates.
Anatomy
[](int x) { return x > 0; } — empty captures, one parameter, a body. Assign to auto or pass directly to an algorithm.
Capture by value [=]
Copies surrounding variables into the lambda at creation — safe to store and call later, but sees stale values if they change.
Capture by reference [&]
Aliases the live variables — sees updates and can modify them, but dangles if the lambda outlives the scope.
Algorithms love lambdas
std::sort(v.begin(), v.end(), [](auto a, auto b) { return a > b; }); sorts descending with the rule defined at the call site.
#include <iostream>#include <vector>#include <algorithm> int main() { std::vector<int> v{3, 1, 2}; int threshold = 1; int big = std::count_if(v.begin(), v.end(), [threshold](int x) { return x > threshold; }); std::cout << big << std::endl; return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.