C/C++ Arena

Step 5 of 6

Captures

A lambda can use variables from the surrounding scope if it captures them:

Capture Meaning
[x] copy of x
[&x] reference to x
[=] copy everything used
[&] reference everything used
int limit = 50;
auto big = std::count_if(v.begin(), v.end(), [limit](int x) { return x > limit; });

int total = 0;
std::for_each(v.begin(), v.end(), [&total](int x) { total += x; });

Your turn: write std::vector<int> above(const std::vector<int>& v, int threshold) that returns the elements greater than threshold, keeping their order. Use std::copy_if with std::back_inserter(out) and a lambda that captures threshold.

Previous: accumulate and transform Next: Erase with a condition