CKTIS / C++
std::count_if: counting elements that satisfy a condition
std::count_if tests every element in a range with a predicate and returns the number of true results.
Version: C++23
Syntax
template<class InputIterator, class Predicate>
constexpr typename std::iterator_traits<InputIterator>::difference_type
count_if(InputIterator first, InputIterator last, Predicate pred);std::count_if(first, last, pred) from <algorithm> evaluates pred(*i) for every iterator i in [first, last) and counts results unequal to false. Its result type is std::iterator_traits<InputIterator>::difference_type; an empty range yields zero.
Let N be the number of elements in the range. The overload without an execution policy makes exactly N predicate applications, so it does not stop after the first match. An input iterator is sufficient; the execution-policy overload requires a forward iterator and may evaluate elements concurrently or without a fixed order.
The predicate must accept the value obtained from the iterator and produce a result convertible to bool. Correctness must not depend on call order, and the predicate must not modify elements through its argument. An exception from user code under any standard execution policy, including seq, calls std::terminate.
Examples
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
const std::vector<int> values{-3, 0, 4, 7, -2};
const auto positive = std::count_if(values.begin(), values.end(),
[](int value) { return value > 0; });
std::cout << positive << '\n';
}
Result
2
std::count_if → 2