Where are lambdas most commonly used?
Short answer
Lambdas are most commonly used as inline callables for STL algorithms (sort comparators, predicates for find_if/count_if/remove_if, transformations), as callbacks and event handlers, in threading (passing work to std::thread or std::async), and anywhere a short, local function…
Advertisement
AModel answer
Lambdas are most commonly used as inline callables for STL algorithms (sort comparators, predicates for find_if/count_if/remove_if, transformations), as callbacks and event handlers, in threading (passing work to std::thread or std::async), and anywhere a short, local function is clearer than a named one.
std::sort(v.begin(), v.end(),
[](int a, int b){ return a > b; }); // descendingReal-world example
A predicate lambda passed to std::remove_if filters out invalid records in one line.
Likely follow-ups
- Which algorithms take predicates? | Why prefer a lambda over a named function here?
Related topics