Advertisement
Beginner C++, Lambda Expressions

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…

Save C++ mock interview
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; }); // descending
Real-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