How to use the count_if() function in C++

The count_if() function is available in the <algorithm.h> header file in C++. This function helps to count the occurrence of elements in the list, based on some condition. If the condition is true, then the element is counted. Otherwise, it is not counted.

Parameters

The count_if() function accepts the following parameters:

  • first: This is the start position of your search space. It is an iterator that usually points to the start of an array.
  • last: This is the end position of your search space. It is an iterator that usually points to the last position of an array.
  • condition: This is an unary function that accepts one element and returns a Boolean value that indicates whether to count that element or not.

Return

The count_if() function returns the number of elements that satisfied the condition.

Let’s now move on to the code.

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool IsEven (int num) {
return (num % 2) == 0;
}
int main () {
vector<int> vec = {1,2,3,4,5,6,7,8,9,10};
int mycount = count_if (vec.begin(), vec.end(), IsEven);
cout << "There are " << mycount << " even numbers.";
return 0;
}

Explanation:

  • From lines 6 to 8, we create the condition function that will return true if the element is even.
  • In line 12, we create a vector of integers.
  • In line 14, we call the count_if() function and pass the condition. Here, we will only count the elements which are even numbers.
  • Finally, in line 15, we print the result.

In this way, we can use count_if() function to count the number of elements that satisfy a certain condition.

Free Resources