C++ Lambda Expressions

C++ lambda expressions are small anonymous functions you can write right where you need them. They are especially useful with STL algorithms like sort, find_if and for_each.

Lambda Syntax

The form is [captures](parameters) { body }. The return type is usually deduced.

#include <iostream>

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

Capturing Variables

  • [x]: capture x by value (a copy)
  • [&x]: capture x by reference
  • [=]: capture everything used by value
  • [&]: capture everything used by reference
  • [this]: capture the current object inside a member function

Capture Example

#include <iostream>

int main() {
    int total = 0;
    int bonus = 5;
    auto addScore = [&total, bonus](int s) { total += s + bonus; };
    addScore(10);
    addScore(20);
    std::cout << "Total: " << total << '\n';
}
Total: 40

Lambdas with STL Algorithms

#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

struct Product { std::string name; double price; };

int main() {
    std::vector<Product> items{{"Tea", 4.5}, {"Rice", 2.0}, {"Oil", 7.25}};
    std::ranges::sort(items, [](const Product& a, const Product& b) {
        return a.price < b.price;
    });
    for (const auto& p : items) std::cout << p.name << ' ' << p.price << '\n';
}
Rice 2
Tea 4.5
Oil 7.25

Generic Lambdas

Using auto parameters makes a lambda work with any type.

#include <iostream>
#include <string>

int main() {
    auto twice = [](const auto& x) { return x + x; };
    std::cout << twice(21) << ' ' << twice(std::string("ab")) << '\n';
}
42 abab

Frequently asked questions

What is a lambda in C++?

A lambda is an unnamed function object defined inline with the syntax [captures](params) { body }. Introduced in C++11, it is widely used with algorithms and callbacks.

What is the difference between capture by value and by reference?

By value copies the variable when the lambda is created, so later changes are not seen. By reference uses the original, so the lambda can change it, but the variable must outlive the lambda.

How do I store a lambda in a variable?

Use auto for the exact type, or std::function<Ret(Args)> when you need a common type, such as storing different lambdas in a container.