Count_if STL Algorithm
The count_if() algorithm returns the number of elements in the sequence beginning at start and ending at end for which the unary predicate and returns true.
template <class InputIterator, class Predicate> typename iterator_traits<InputIterator>::difference_type count_if ( ForwardIterator first, ForwardIterator last, Predicate pred ); Return number of elements in range satisfying condition Returns the number of elements in the range [first,last) for which condition pred is true.
Implementation of count_if() algorithm
#include <iostream> #include <algorithm> #include <vector> using namespace std; typedef int type; const int size=10; const int target=5; int less_than(int value) { return value<target; } int main () { type const list[size]= {1,3,9,4,20,40}; vector<type> vec0(list,list+6); type result; result = count_if (vec0.begin(), vec0.end(), less_than); cout << "contains " << result << " values less that "<< target<< endl; return 0; }// end of main
Program Output:
contains 3 values less that 5