Algorithm Count If Function - C++ Programming Tutorial
C++ Course / STL Algorithm / Algorithm Count If Function

Algorithm Count If Function

BLUF: Mastering Algorithm Count If Function is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Algorithm Count If Function

C++ is renowned for its efficiency. Learn how Algorithm Count If Function enables low-level control and high-performance computing in the tutorial below.

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

Example

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

Example

#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:

Output

newvector contains 5 odd values.

Example 2

Example

#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:

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.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience