# count_if() in C++ STL

C++Server Side ProgrammingProgramming

In this article we will be discussing the working, syntax and examples of std::count_if() function in C++ STL.

## What is std::count_if()?

std::count_if() function is an inbuilt function in C++ STL, which is defined in <algorithm> header file. count_if() is used to get the number of elements in a specified range which satisfy a condition. This function returns an integer value which is the number of elements which satisfies the condition.

The function not only iterates through the given range but also checks if the statement or condition is true and counts how many times the statement or condition was true and returns the result.

## Syntax

count_if(start, end, condition);

## Parameters

The function accepts the following parameter(s) −

• start, end − These are the iterators which can be used to give a range in which we have to use the function. start gives the beginning position of the range and end gives the ending position of the range.
• condition − This is the condition which we want to check. Condition is the unary function which has to be applied on the given range.

## Return value

This function returns the number of elements which are meeting the condition.

## Input

bool iseve(int i){ return ((i%2)==0); }
int a = count_if( vect.begin(), vect.end(), iseve ); /* vect has 10 integers 1-10*/

## Output

even numbers = 2 4 6 8 10

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
bool check_odd(int i){
if (i % 2!= 0)
return true;
else
return false;
}
int main() {
vector<int> vec;
for (int i = 0; i < 10; i++){
vec.push_back(i);
}
int total_odd = count_if(vec.begin(), vec.end(), check_odd);
cout<<"Number of odd is: "<<total_odd;
return 0;
}

## Output

Number of odd is: 5