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.
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.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;}
true
if the element is even.count_if()
function and pass the condition. Here, we will only count the elements which are even numbers.In this way, we can use count_if()
function to count the number of elements that satisfy a certain condition.