Lambda Captures
Completed
Read n integers and a threshold t. Using a lambda that captures t by value and a counter by reference, count the values above t and print them and the count.
Input
n, the integers, then t.
Output
Two lines.
Example
Input
6 5 12 7 20 1 9 6
Output
12 7 20 9 4
Editor
C++
Hints
[t] copies t into the lambda; [&count] lets the lambda modify count.
Solution explanation
The capture list controls what a lambda can see and whether it can change it.
Show solution
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n, t;
cin >> n;
vector<int> v(n);
for (int &x : v) cin >> x;
cin >> t;
int count = 0;
vector<int> above;
for_each(v.begin(), v.end(), [t, &count, &above](int x) {
if (x > t) {
count++;
above.push_back(x);
}
});
for (size_t i = 0; i < above.size(); i++) cout << above[i] << (i + 1 < above.size() ? " " : "");
cout << "\n" << count << "\n";
return 0;
}