Lambdas and Function Objects
Treating behaviour as data: callables you can pass, store, and compose
operator(); and std::function is a uniform box that can hold any of them. Together they let you pass logic into algorithms, register callbacks, and build reusable strategies.
- read and write the full lambda syntax
[captures](params) -> ret { body }, - capture variables by value, by reference, and with init-capture,
- write a functor and explain how a lambda compiles down to one,
- store any callable in
std::functionand know what that costs.
1. What is a lambda, and why?
Think of a lambda as a sticky note with an instruction. Instead of writing a full named function somewhere else and referring back to it, you write the instruction on the spot and hand it to whoever needs it. The reader (an algorithm, a thread, a button) can run it later, as many times as it likes.
Before C++11, if you wanted to give std::sort a custom ordering you had to write a separate named function or a functor struct far away from the call site. That scattered the logic and hurt readability. A lambda expression lets you define the function inline:
#include <algorithm>
#include <vector>
std::vector<int> v = {5, 2, 8, 1};
// Sort in DESCENDING order using an inline comparator:
std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; });
// v is now {8, 5, 2, 1}
The [](int a, int b) { return a > b; } part is the whole function, written where it is used. It has no name of its own; the compiler quietly generates one for you.