Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All
Expand Minimize
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.


Returns the number of elements in a range whose values satisfy a specified condition.

template<class InputIterator, class Predicate> 
   typename iterator_traits<InputIterator>::difference_type count_if( 
      InputIterator _First,  
      InputIterator _Last, 
      Predicate _Pred 


An input iterator addressing the position of the first element in the range to be searched.


An input iterator addressing the position one past the final element in the range to be searched.


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.

The number of elements that satisfy the condition specified by the predicate.

This template function is a generalization of the algorithm count, replacing the predicate "equals a specific value" with any predicate.

// alg_count_if.cpp
// compile with: /EHsc
#include <vector>
#include <algorithm>
#include <iostream>

bool greater10(int value)
    return value >10;

int main()
    using namespace std;
    vector<int> v1;
    vector<int>::iterator Iter;


    cout << "v1 = ( ";
    for (Iter = v1.begin(); Iter != v1.end(); Iter++)
        cout << *Iter << " ";
    cout << ")" << endl;

    vector<int>::iterator::difference_type result1;
    result1 = count_if(v1.begin(), v1.end(), greater10);
    cout << "The number of elements in v1 greater than 10 is: "
         << result1 << "." << endl;
v1 = ( 10 20 10 40 10 ) The number of elements in v1 greater than 10 is: 2.

Header: <algorithm>

Namespace: std

Community Additions

© 2015 Microsoft