Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::count: counting elements equal to a value

std::count traverses an entire range, compares each element with a value, and returns the hit count in the iterator’s difference_type.

Version: C++23

Syntax

template<class InputIterator, class T>
constexpr typename std::iterator_traits<InputIterator>::difference_type
count(InputIterator first, InputIterator last, const T& value);

std::count(first, last, value) from <algorithm> returns the number of iterators i in [first, last) for which *i == value. Its result type is std::iterator_traits<InputIt>::difference_type. An empty range produces zero.

Let N be the number of elements in [first, last). The algorithm performs exactly N comparisons and does not stop early. An input iterator is sufficient and a single pass is possible. Elements are not modified, but equality must be valid for the compared types.

The execution-policy overload requires forward iterators and may perform comparisons in a different order or concurrently. A comparison exception under any standard policy, including seq, calls std::terminate; comparison must not introduce a data race. std::ranges::count is a separate interface that also supports a projection.

Examples

#include <algorithm>
#include <iostream>
#include <vector>

int main() {
    const std::vector<int> values{2, 1, 2, 3, 2};
    std::cout << std::count(values.begin(), values.end(), 2) << '\n';
}

Result

3

std::count → 3

Sources