The count_if function in C++ algorithms requires a predicate 'pred' and calculates the number of elements within the range [first, last) that satisfy the predicate condition.
Syntax
template <class InputIterator, class UnaryPredicate>
typename iterator_traits<InputIterator>::difference_type count_if(InputIterator first, InputIterator last,UnaryPredicate pred);
Parameter
It serves as an input iterator pointing to the initial element within the specified range.
It serves as an input iterator pointing to the final element within the specified range.
It represents the element that is being sought after within the specified range.
Return value
The function retrieves the count of elements within the range [first, last) that satisfy the condition specified by pred.
Example 1
#include<iostream>
#include<algorithm>
#include<vector>
bool isOdd(int k)
{
return((k%2)==1);
}
int main()
{
std::vector<int> newvector;
for(int k=1; k<10; k++)
newvector.push_back(k);
int newcount=count_if(newvector.begin(),newvector.end(),isOdd);
std::cout<<"newvector contains "<<newcount<<" odd values.\n";
return 0;
}
Output:
newvector contains 5 odd values.
Example 2
#include<bits/stdc++.h>
using namespace std;
bool isEven(int k)
{
if(k%2==0)
return true;
}
int main()
{
vector<int> u;
for(int i=0; i<10; i++)
{
u.push_back(i);
}
int noEven=count_if(u.begin(),u.end(),isEven);
cout<<"Count of even number is:"<<noEven;
return 0;
}
Output:
Count of even number is: 10
Complexity
The function's complexity increases linearly based on the distance between the initial and final elements.
Data races
Accessing some or all of the components within the range occurs.
Exceptions
The function will raise an exception if any of the arguments also raises an exception.