Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

count_if() in C++ STL

  • Difficulty Level : Easy
  • Last Updated : 31 May, 2021

count_if() function returns the number of elements in a range that satisfy the condition.


template <class InputT, class UnaryPredicate>
typename iterator_traits <InputT> :: difference_type
    count_if(InputT first, InputT last, UnaryPredicate p);


Input: 0 1 2 3 4 5 6 7 8 9
Output: Total no of even numbers is: 5

Input: 2 3 4 5 6 7 8 9 10 11 12 13
Output: Total no of even numbers is: 6

The count_if function takes three parameters, the first two of which are the first and the last position of the sequence of the elements (where the last position is not included in the range) while the third parameter is an unary predicate ( takes single argument to check the condition and returns true or false ) that takes the element of given sequence one by one as a parameter and returns a boolean value on the basis of condition 
specified in that function.  One thing we should keep in mind is that type of the predicate should be same as the type of the container. 

Then, count_if() returns the number of elements in the given sequence for which the comparator function 
(third parameter) returns true.


// C++ program to show the working
// of count_if()
#include <bits/stdc++.h>
using namespace std;
// Function to check the
// number is even or odd
bool isEven(int i)
    if (i % 2 == 0)
        return true;
        return false;
// Drivers code
int main()
    vector<int> v;
    for (int i = 0; i < 10; i++) {
    int noEven = count_if(v.begin(), v.end(),
    cout << "Total no of even numbers is: "
         << noEven;
    return 0;
Total no of even numbers is: 5


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!