C++ Standard Library C++ STL Library

C++ <algorithm> - count_if() Function



The C++ algorithm::count_if function returns the number of elements in the range [first, last) for which the unary function pred returns true.

Syntax

template <class InputIterator, class UnaryPredicate>
  typename iterator_traits<InputIterator>::difference_type
    count_if (InputIterator first, 
              InputIterator last, 
              UnaryPredicate pred);

Parameters

first Specify initial position of the input iterator. The range used is [first,last).
last Specify final position of the input iterator. The range used is [first,last).
pred Specify an unary function that accepts an element in the range as argument, and returns a value convertible to bool. The element will be counted if the function returns true.

Return Value

Returns number of elements in the range for which pred returns true.

Time Complexity

Linear i.e, Θ(n).

Example:

In the example below, the algorithm::count_if function is used to find out the number of occurrences of specified value in the given vector.

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std; 

bool isEven (int i) {return (i%2==0);}

int main (){
  vector<int> vec{11, 12, 13, 14, 15, 16, 17};

  //count of even numbers in the vector
  int retval1 = count_if(vec.begin(), vec.end(), isEven);
  cout<<"Count of even numbers: "<<retval1<<endl;

  //count of odd numbers in the vector
  int retval2 = count_if(vec.begin(), vec.end(), [](int i) {return (i%2==1);});
  cout<<"Count of odd numbers: "<<retval2<<endl;

  return 0;
}

The output of the above code will be:

Count of even numbers: 3
Count of odd numbers: 4

❮ C++ <algorithm> Library