count() in C++ STL

The C++ Standard Library consists of the header, <algorithm> which defines a collection of functions (principally designed to deal with a range of elements). count() is a method in the STL that returns the number of elements in a range that are equal to a certain value.

Syntax:

count( iterator_begin, iterator_end, val);

Parameters: The count() method accepts 3 parameters

  • iterator_begin: Iterator to the initial position
  • iterator_end: Iterator to the final position ( Note: the range is [iterator_begin,iterator_end) )
  • val: Value to match

Return value: Number of elements in the range equal to val

Example of count() method

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

using namespace std;


int main()
{
    vector<int> v;
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    v.push_back(4);
    v.push_back(3);
    v.push_back(5);
    v.push_back(3);

    cout<<"Number of times 3 is repeated: "<< count(v.begin(), v.end(), 3) << endl;
}

Output:

Number of times 3 is repeated: 3

This article is written by

Please comment below, if you have any doubts or find any error in the above article.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top