The count function in C++ Algorithm takes 'val' as a parameter and checks for the presence of the specified element 'val' within the given range. It then returns the count of how many times that element appears in the range.
Syntax
template <class InputIterator, class T>
typename iterator_traits<InputIterator>::difference_type count (InputIterator first, InputIterator last, const T& val);
Parameter
It serves as an input iterator pointing to the initial element within the specified range.
The final iterator points to the last element within the specified range.
val : It represents the item being sought within the specified range.
Return value
The function retrieves the count of appearances of the item 'val' within the interval [first, last).
Example 1
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
int newints[]={50,60,70,70,60,50,50,60};
int newcount=std::count(newints, newints+8, 50);
std::cout<<"50 appear "<<newcount<<"times.\n";
std::vector<int> newvector(newints, newints+8);
newcount=std::count(newvector.begin(),newvector.end(),70);
std::cout<<"70 appear "<<newcount<<"times.\n";
return 0;
}
Output:
50 appear 3 times.
70 appear 2 times.
Example 2
#include <bits/stdc++.h>
using namespace std;
int main()
{
int ar[]={6,4,2,6,6,10,6};
int n = sizeof(ar)/sizeof(ar[0]);
cout<<"The number of times 6 appear is:"<<count(ar,ar+n,6);
return 0;
}
Output:
The number of times 6 appear is: 4
Complexity
The function's complexity increases linearly based on the distance between the initial and final elements.
Data races
Some or all of the components within the range are retrieved.
Exceptions
The function will raise an exception if any of the arguments also raises an exception.