Answer questions about a list with standard algorithms.
What to build
Two algorithms, each given the same test function.
Requirements
- A mark of 40 or more is a pass.
- Print
passed N, usingcount_if. - Print
first F, the first passing mark, usingfind_if, orfirst none.
Input
The first line has n. The second line has n whole numbers.
Output
Two lines.
Constraints
n is from 1 to 1000, and marks are from 0 to 100.
Example
Input:
4
30 72 35 90
Output:
passed 2
first 72
Why it works
The algorithms do the looping, and the single test function states the rule in one place.
Examples
Example 1 · Input
4 30 72 35 90
Expected output
passed 2 first 72
Example 2 · Input
2 1 2
Expected output
passed 0 first none
Hints
Hint 1
Write bool passed(int mark).
Hint 2
Use count_if and find_if.
Hint 3
Compare the result of find_if with end().
Solution
Show one correct solution (try it yourself first)
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
bool passed(int mark) {
return mark >= 40;
}
int main() {
int n;
cin >> n;
vector<int> v(n);
for (int& x : v) cin >> x;
cout << "passed " << count_if(v.begin(), v.end(), passed) << endl;
auto it = find_if(v.begin(), v.end(), passed);
if (it == v.end()) {
cout << "first none" << endl;
} else {
cout << "first " << *it << endl;
}
return 0;
}