If you want to count the presence of a element in a given range, then you can use the count() function defined in the STL algorithm.
It returns the number of variable inside a range whose value is equal to the given number.
Template for count
template <class InputIterator, class T>
count (InputIterator first, InputIterator last, const T& val);
About parameters InputIterator first
InputIterator for the initial position of the range which is included in the range. InputIterator last
InputIterator for the final position which it not included in the range. val
value to count in the given range.
Sample program using count
using namespace std;
vector <int> v;
vector <int>:: iterator it;
// Pushing 11 random integer elements inside the vector
// printing the elements inside the range
cout <<"Elements inside the range " << endl;
for ( it = v.begin(); it != v.end(); it++)
cout << *it << " ";
cout << endl;
//counting the occourance of 2 in range
result = count(v.begin(),v.end(),2);
cout <<"2 found " << result << " times in the range." << endl;
//counting the occourance of 23 in range
result = count(v.begin(),v.end(),23);
cout <<"23 found " << result << " times in the range." << endl;
Output of the above program
Elements inside the range
1 2 3 4 2 5 2 6 21 6 2
2 found 4 times in the range.
23 found 0 times in the range.
Time complexity for count is linear in between the range.