Lambda expressions create anonymous function objects inline—ideal for STL algorithms and short callbacks, similar in spirit to arrow functions in JavaScript.
Syntax
int factor = 2;
auto scale = [factor](int x) { return x * factor; };
std::cout << scale(21) << "\n";
Capture [=] by value, [&] by reference, or list specific names.
With algorithms
std::sort(v.begin(), v.end(), [](int a, int b) {
return a > b;
});
Important interview questions and answers
- Q: Capture gotcha?
A: `[&]` referencing locals that die before the lambda runs causes dangling references—capture by value or ensure lifetime. - Q: Generic lambda?
A: C++14autoparameters create templated call operator.
Self-check
- What does [&] capture?
- Where are lambdas commonly used in STL?
Pitfall: Lambdas capturing locals by reference ([&]) dangle if the lambda outlives the scope—capture by value for async callbacks.
Interview prep
- [&] capture danger?
Capturing locals by reference in lambdas that outlive the scope causes dangling references.
- Lambdas with STL?
Pass lambdas to
sort,find_if,for_each, and other algorithms.