typestar

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

  1. std::ranges::find returns an iterator to the first match, or v.end() when there is none.
  2. std::ranges::count tallies exact matches; here it checks that no element is 0.
  3. std::ranges::count_if takes a lambda, counting the evens; the three answers combine into one bool.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in Algorithms, step 15 of 27 in Language basics.

← Previous Next →