← C++ from Scratch Lesson 33 of 62 · 10 XP

Lambdas

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

A lambda is a function without a name, written right where it's needed:

auto add = [](int a, int b) { return a + b; };
add(2, 3);   // 5

int bonus = 10;
auto withBonus = [bonus](int x) { return x + bonus; };   // [bonus] — capture a copy
auto addTo = [&bonus](int x) { bonus += x; };            // [&bonus] — capture by reference

std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; });   // sort in descending order

[ ] is the capture: which outside variables the lambda can see ([=] — all by value, [&] — all by reference). Lambdas are most often passed to STL algorithms: sorting, searching, counting (module 7).

Task. Read n and n numbers into a std::vector<int>, then a threshold t. Using std::count_if and a lambda that captures t, print how many numbers are greater than t. Then sort the vector in descending order with a comparator lambda and print it.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.