Skip to main content

9.5) Algorithm Examples: Counting Occurrences Of A Value


count requires a pair of iterators and the value to be counted:

vector<int> v;
...
int num_zeros = count(v.begin(), v.end(), 0);

count_if requires a pair of iterators and a predicate function that returns true if a value should be counted, false otherwise:

bool is_negative(int value)
{
  return value < 0;
}
...
int num_negative = count_if(v.begin(), v.end(), is_negative);

See count.cpp and countif.cpp for complete examples.