C++ Standard Library C++ STL Library

C++ <algorithm> - count() Function



The C++ algorithm::count function returns the number of occurrences of specified value val in the range [first, last).

Syntax

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

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).
val Specify the value to be counted.

Return Value

Returns number of occurrences of val in the range [first, last).

Time Complexity

Linear i.e, Θ(n).

Example:

In the example below, the algorithm::count 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; 

int main (){
  vector<int> vec{10, 20, 30, 10, 10, 20, 50};

  //find out the number of occurrences of 10
  int retval1 = count(vec.begin(), vec.end(), 10);
  cout<<"Number of occurrences of 10: "<<retval1<<endl;

  //find out the number of occurrences of 20
  int retval2 = count(vec.begin(), vec.end(), 20);
  cout<<"Number of occurrences of 20: "<<retval2;

  return 0;
}

The output of the above code will be:

Number of occurrences of 10: 3
Number of occurrences of 20: 2

❮ C++ <algorithm> Library

5