TExcelTAD
Home › C++ › C++ Lambdas

C++ Lambdas

A lambda expression is a small, unnamed function that you write right where you need it. Lambdas were added in C++11 and are everywhere in modern C++ — especially as arguments to standard algorithms like sort, count_if and for_each.

Syntax

cpp
[capture](parameters) -> return_type { body }
  • [capture] — which variables from the surrounding code the lambda may use.
  • (parameters) — like a normal function's parameter list.
  • -> return_type — optional; usually the compiler deduces it.
  • { body } — the code.
cpp · try it yourself
#include <iostream>
using namespace std;

int main() {
    auto square = [](int x) { return x * x; };
    auto greet = []() { cout << "Hi from a lambda\n"; };

    cout << square(9) << "\n";
    greet();

    // a lambda can also be called immediately
    int result = [](int a, int b) { return a * 10 + b; }(4, 2);
    cout << result << "\n";
}
81
Hi from a lambda
42

Each lambda has a unique type that only the compiler knows, so you store it in an auto variable.

Lambdas with algorithms

This is where lambdas shine. Algorithms take a function telling them how to compare, filter or transform, and a lambda supplies it inline:

cpp · try it yourself
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

int main() {
    vector<string> words = {"kiwi", "banana", "fig", "cherry", "apple"};

    stable_sort(words.begin(), words.end(), [](const string& a, const string& b) {
        return a.size() < b.size();          // shortest first
    });
    for (const auto& w : words) cout << w << " ";
    cout << "\n";

    int longOnes = count_if(words.begin(), words.end(),
                            [](const string& w) { return w.size() > 4; });
    cout << longOnes << " words longer than 4 letters\n";
}
fig kiwi apple banana cherry
3 words longer than 4 letters

We used stable_sort so that words of equal length (banana and cherry) keep their original relative order; plain sort makes no such promise.

Captures

A lambda cannot use local variables of the enclosing function unless it captures them:

Capture Meaning
[] capture nothing
[x] copy x into the lambda
[&x] refer to x by reference
[=] copy everything used
[&] reference everything used
[this] access the current object's members (inside classes)
cpp · try it yourself
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> nums = {3, 14, 7, 22, 9, 30};
    int threshold = 10;
    int total = 0;

    // threshold copied in, total captured by reference so it can be updated
    for_each(nums.begin(), nums.end(), [threshold, &total](int n) {
        if (n > threshold) total += n;
    });
    cout << "Sum of values above " << threshold << ": " << total << "\n";

    int factor = 3;
    auto byCopy = [factor](int n) { return n * factor; };
    auto byRef  = [&factor](int n) { return n * factor; };
    factor = 100;
    cout << byCopy(2) << " " << byRef(2) << "\n";
}
Sum of values above 10: 66
6 200

The copy was taken when the lambda was created, so byCopy still uses 3. The reference sees the later change to 100.

Mutable lambdas and state

Captured copies are read-only by default. Add mutable to let the lambda modify its own copy — this gives the lambda private state:

cpp · try it yourself
#include <iostream>
using namespace std;

int main() {
    auto counter = [count = 0]() mutable {
        return ++count;
    };
    cout << counter() << " " << counter() << " " << counter() << "\n";
}
1 2 3

[count = 0] is an init-capture (C++14): it creates a new variable inside the lambda.

Storing lambdas: std::function

To keep lambdas with different captures in one variable or container, use std::function from <functional>. It can hold anything callable with a matching signature:

cpp · try it yourself
#include <iostream>
#include <functional>
#include <map>
#include <string>
using namespace std;

int main() {
    map<string, function<double(double, double)>> ops = {
        {"add", [](double a, double b) { return a + b; }},
        {"mul", [](double a, double b) { return a * b; }},
        {"pow2", [](double a, double)  { return a * a; }}
    };
    for (const auto& [name, fn] : ops) {
        cout << name << "(6, 7) = " << fn(6, 7) << "\n";
    }
}
add(6, 7) = 13
mul(6, 7) = 42
pow2(6, 7) = 36

Tip: Prefer capturing explicitly ([x, &y]) over [=] and [&], and be careful with & captures: if the lambda outlives the captured variable, the reference dangles.

Test yourself

What does the capture [&total] do?

  1. Copies total into the lambda
  2. Captures total by reference
  3. Captures everything by reference
  4. Makes total const

With int k = 1; auto f = [k]{ return k; }; k = 5;, what does f() return?

  1. 1
  2. 5
  3. 0
  4. Compile error

Which keyword lets a lambda modify its by-copy captures?

  1. static
  2. mutable
  3. volatile
  4. var