12.3 — Lambdas in depth

📘 Chapter 12⏱ about 2 min read✍️ Beginner friendly
Read one box at a time. No rush.

A quick recap#

A lambda is a function with no name, written right where you need it (11.2 — The algorithm toolbox).

C++
auto square { [](int x) { return x * x; } };std::cout << square(5);   // 25

The parts#

C++
[capture](parameters) { body }
  • [ ] = the capture list: which outside variables the lambda can use.
  • ( ) = parameters, just like a normal function.
  • { } = the steps.

Capturing variables#

A lambda can't see the variables around it unless you capture them.

C++
int limit { 10 }; auto isBig { [limit](int x) { return x > limit; } };   // copy of limitstd::cout << std::boolalpha << isBig(15);              // true
CaptureMeaning
[]capture nothing
[x]a copy of x
[&x]x itself, by reference (changes stick)
[=]copies of everything used
[&]everything used, by reference

Changing a captured variable#

Capture by reference to change it:

C++
int clicks { 0 };auto click { [&clicks]() { ++clicks; } }; click();click();std::cout << clicks;   // 2

Lambdas + algorithms#

C++
std::vector<std::string> names { "Ana", "Bartholomew", "Cleo" }; auto longOne { std::find_if(names.begin(), names.end(),    [](const std::string& n) { return n.length() > 5; }) }; if (longOne != names.end())    std::cout << *longOne << '\n';   // Bartholomew
Watch out

Be careful with [&] if the lambda is kept and used later. If the variables it refers to are gone by then, the references dangle.

Good habit

List captures by name ([limit], [&clicks]) rather than [=] or [&]. It makes clear exactly what the lambda uses.

Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.