devnotes.

Lambda Expressions

Lambda expressions (C++11) let you define a small, anonymous function directly inline, right where it's needed — most commonly as an argument to an STL algorithm.

auto add = [](int a, int b) { return a + b; };
std::cout << add(3, 4) << "\n";   // 7

int total = 0;
auto addToTotal = [&total](int x) { total += x; };  // capture by reference
addToTotal(10);
std::cout << total << "\n";        // 10

int factor = 3;
auto multiply = [factor](int x) { return x * factor; }; // capture by value (a copy)

std::vector<int> nums = {5, 2, 8, 1};
std::sort(nums.begin(), nums.end(), [](int a, int b) {  // inline comparator
    return a > b;   // descending
});

The square brackets [] are the capture clause, controlling which surrounding variables the lambda can access and how: [] captures nothing, [x] captures x by value (a snapshot, copied at the point the lambda is created), [&x] captures x by reference (always reflects x's current value), and [&]/[=] capture everything used in the body by reference or by value respectively.

Lambdas are most valuable exactly where a tiny, one-off function is needed but writing and naming a full separate function would be overkill — a custom sort comparator, a filter predicate, a callback for std::for_each. C++14 extended lambdas with generic parameters ([](auto a, auto b) { return a + b; }, working like a template), and C++20 further allows lambdas to be genuinely constexpr and to capture with an explicit template parameter list — but the basic capture-and-call pattern shown above covers the overwhelming majority of everyday use.

Lambda Expressions in C++ | DevNotes