C++ Lambda Expressions

A lambda (C++11) is a small nameless function which you write in place. It is mostly used with algorithms.

#include <iostream>

int main() {
    auto add = [](int a, int b) { return a + b; };
    std::cout << add(3, 4) << '\n';
    std::cout << [](int x) { return x * x; }(5) << '\n';       // call at once
}
Output

7
25

The capture list

The square brackets say which variables of the outside the lambda can use.

CaptureMeaning
[]Nothing
[x]x by value (a copy)
[&x]x by reference
[=]Everything by value
[&]Everything by reference
#include <iostream>

int main() {
    int factor = 3;
    int counter = 0;

    auto by_value = [factor](int n) { return n * factor; };
    auto by_ref = [&counter](int n) { counter += n; };
    auto changes_copy = [counter]() mutable { counter += 100; return counter; };

    std::cout << by_value(5) << '\n';
    by_ref(10); by_ref(5);
    std::cout << counter << '\n';
    std::cout << changes_copy() << ' ' << counter << '\n';       // the original is not changed
}
Output

15
15
100 15

With algorithms

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

int main() {
    std::vector<int> v = {5, 12, 8, 3, 20};
    int limit = 7;

    auto big = std::count_if(v.begin(), v.end(), [limit](int n) { return n > limit; });
    std::cout << big << '\n';

    std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; });
    for (int n : v) std::cout << n << ' ';
    std::cout << '\n';
}
Output

3
20 12 8 5 3

Generic lambda and std::function

#include <functional>
#include <iostream>
#include <string>

int main() {
    auto print = [](const auto& x) { std::cout << x << '\n'; };      // works for any type
    print(42);
    print("text");
    print(2.5);

    std::function<int(int)> twice = [](int n) { return n * 2; };    // store any callable
    std::cout << twice(21) << '\n';

    auto make_adder = [](int n) { return [n](int x) { return x + n; }; };
    std::cout << make_adder(10)(5) << '\n';
}
Output

42
text
2.5
42
15

Dangling references

A lambda which captures by reference must not live longer than the variable. A lambda returned from a function should capture by value.

Note: Prefer capturing the exact variables you need, like [limit], and not [=] or [&]. It makes the code clear. Next: C++ File Handling.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.