find & count in C++
Three questions about a vector, each answered in one algorithm call instead of a hand-rolled loop.
#include <algorithm>
#include <vector>
bool found_enough(const std::vector<int>& v, int target) {
auto hit = std::ranges::find(v, target); // iterator, or end()
auto zeros = std::ranges::count(v, 0);
auto evens = std::ranges::count_if(v, [](int x) { return x % 2 == 0; });
return hit != v.end() && zeros == 0 && evens >= 2;
}
How it works
std::ranges::findreturns an iterator to the first match, orv.end()when there is none.std::ranges::counttallies exact matches; here it checks that no element is0.std::ranges::count_iftakes a lambda, counting the evens; the three answers combine into onebool.
Keywords and builtins used here
autoboolconstfound_enoughintreturn
The run, in numbers
- Lines
- 9
- Characters to type
- 327
- Tokens
- 111
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 89 seconds.
Step 3 of 3 in Algorithms, step 15 of 27 in Language basics.