count
Count appearances of value in range
Definition
The count() algorithm is defined in the standard header <algorithm> and in the nonstandard backward-compatibility header <algo.h>.
Interface
#include <algorithm>
template < class InputIterator, class Type>
typename iterator_traits<InputIterator>::difference_type count(
InputIterator first,
InputIterator last,
const Type& val
);Parameters:
| Parameter | Description |
| first | An input iterator addressing the position of the first element in the range to be traversed |
| last | An input iterator addressing the position one past the final element in the range to be traversed |
| val | The value of the elements to be counted |
Description
Count the number of values in an input range [first,last) that equal val.
Return Value
Count algorithm returns the number of iterators i in [first, last) such that *i == value.
Complexity
The complexity is linear. Exactly last - first comparisons.
Example 1
Problem
This short program illustrates the functionality of count() algorithm.
Workings
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
vector<int> v1;
vector<int>::iterator Iter;
v1.push_back(10);
v1.push_back(20);
v1.push_back(10);
v1.push_back(40);
v1.push_back(10);
cout <<"v1 = ( " ;
for (Iter = v1.begin(); Iter != v1.end(); Iter++)
cout <<*Iter<<" ";
cout <<")"<<endl;
vector<int>::iterator::difference_type result;
result = count(v1.begin(), v1.end(), 10);
cout <<"The number of 10s in v2 is: "<<result<<"."<<endl;
return 0;
}Solution
Output:
v1 = ( 10 20 10 40 10 )
The number of 10s in v2 is: 3.