Lambdas
A lambda is an anonymous function you write at the call site. The compiler turns it into a unique class with operator(), so you can pass behaviour into std::sort, std::find_if, or a thread without naming a function.
Detailed Explanation
You want std::sort to order users by last login, not by operator<. Before C++11 you wrote a function or a function object class, gave it a name, and passed that name in. The predicate lived far from the call. A lambda writes the predicate where it is used: std::sort(u.begin(), u.end(), [](const User& a, const User& b) { return a.lastLogin > b.lastLogin; });.
The syntax is [captures](parameters) specifiers { body }. Captures are a separate page; they are how the lambda sees local variables. Parameters look like a function's. The body is ordinary C++. The whole expression creates a temporary object of an unnamed class, called the closure type. Each lambda expression has a distinct type. Two lambdas with identical text still have different types.
That object is callable. auto add = [](int a, int b) { return a + b; }; add(1, 2); is 3. Because the type has no name, you store it in auto, pass it to a template, or wrap it in std::function<int(int, int)> when you need a named type (a member, a return across a .cpp boundary). std::function can allocate and goes through a virtual call. A template parameter (template<class F> void apply(F f)) inlines the lambda and is the default for algorithm-style APIs.
Return type is deduced from return statements in C++14, or written with a trailing type: [](int n) -> double { return n; }. If the body has no return, the type is void.
Specifiers you will actually write:
mutablelets a lambda that captured by value modify its copy. Without it,operator()isconst.constexpr(C++17) / implicit constexpr when the body allows it.noexceptwhen the lambda does not throw.consteval(C++20) for an immediate lambda.
A lambda with an empty capture [] and no auto parameters can convert to a function pointer. That is how you pass one to a C API that wants int(*)(int). A capturing lambda cannot, because the function pointer has nowhere to put the captured state. Use a void* userdata pattern or keep the lambda on the C++ side.
C++14 generic lambdas accept auto parameters: [](const auto& x) { return x.size(); }. That is a template operator(). C++20 added template heads: []<class T>(const std::vector<T>& v) { ... }.
Lambdas exist to be small. If the body is twenty lines or has several returns, it is a named function. If you need to unit-test the logic, it is a named function. The lambda is for the glue that is obvious in context: a comparator, a filter, a tiny callback.
Code Examples
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
int main() {
std::vector<std::string> names{"grace", "ada", "al"};
std::sort(names.begin(), names.end(),
[](const std::string& a, const std::string& b) {
return a.size() < b.size();
});
for (const auto& n : names) std::cout << n << ' ';
std::cout << '\n'; // prints: al ada grace
auto add = [](int a, int b) { return a + b; };
std::cout << add(2, 3) << '\n'; // prints: 5
}#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> nums{1, 2, 3, 4, 5};
int threshold = 3;
auto count = std::count_if(nums.begin(), nums.end(),
[threshold](int n) { return n > threshold; });
std::cout << count << '\n'; // prints: 2
}Common Gotchas
A capturing lambda is not a function pointer
`qsort` and many C callbacks will not accept `[n](int x){ return x > n; }`. Give them a `[]` lambda or a plain function, and pass state through a userdata pointer.
Default `operator()` is `const`
incrementing a by-value capture requires `mutable`. Otherwise you get a compiler error about assigning in a const method.
Each lambda has a unique type
you cannot put two different lambdas in a `std::vector` without erasing them (`std::function`, a common base, or a `std::variant` of the closure types).