Learn C++
#include "functions/lambdas.hpp"

Lambda Expressions in C++

//concept

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.

//how it works
1

Anatomy

[](int x) { return x > 0; } — empty captures, one parameter, a body. Assign to auto or pass directly to an algorithm.

2

Capture by value [=]

Copies surrounding variables into the lambda at creation — safe to store and call later, but sees stale values if they change.

3

Capture by reference [&]

Aliases the live variables — sees updates and can modify them, but dangles if the lambda outlives the scope.

4

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.

//example
#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;
}
Output
2
1[threshold] captures the local by value, so the body can compare against 1.
2count_if tests 3, 1, 2 — true for 3 and 2, false for 1 — counting 2 matches.
3No named function was needed; the predicate lived exactly where it was used.
//use cases
Custom sort orders, filters, and transforms inline at algorithm call sites
Capturing local context for callbacks without writing functor classes
Accumulating into locals via [&] captures in for_each and friends
Generic auto-parameter lambdas as shorthand for simple function templates

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.