count
template<class InputIterator, class Type>
typename iterator_traits<InputIterator>::difference_type count(
InputIterator _First,
InputIterator _Last,
const Type& _Val
);
Parameters
_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.
Return Value
The difference type of the InputIterator that counts the number of elements in the range [ _First, _Last ) that have value _Val.
Remarks
The operator== used to determine the match between an element and the specified value must impose an equivalence relation between its operands.
count_if
template<class InputIterator, class Predicate>
typename iterator_traits<InputIterator>::difference_type count_if(
InputIterator _First,
InputIterator _Last,
Predicate _Pred
);
Parameters
_First
An input iterator addressing the position of the first element in the range to be searched.
_Last
An input iterator addressing the position one past the final element in the range to be searched.
_Pred
User-defined predicate function object that defines the condition to be satisfied if an element is to be counted. A predicate takes single argument and returns true or false.
Return Value
The number of elements that satisfy the condition specified by the predicate.
Remarks
This template function is a generalization of the algorithm count, replacing the predicate "equals a specific value" with any predicate.
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool cmp(int& a)
{
return a < 5;
}
int main()
{
vector<int>test;
test.push_back(1);
test.push_back(1);
test.push_back(1);
test.push_back(8);
test.push_back(2);
vector<int>::iterator::distance_type res;
res = count(test.begin(), test.end(), 1);
cout << res << endl;
res = count_if(test.begin(), test.end(), cmp);
cout << res << endl;
getchar();
return 0;
}