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

Algorithm Count Function

BLUF: Mastering Algorithm Count 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 Function

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

The count function in C++ Algorithm takes 'val' as a parameter and checks for the presence of the specified element 'val' within the given range. It then returns the count of how many times that element appears in the range.

Syntax

Example

template <class InputIterator, class T>

typename iterator_traits<InputIterator>::difference_type count (InputIterator first, InputIterator last, const T& val);

Parameter

It serves as an input iterator pointing to the initial element within the specified range.

The final iterator points to the last element within the specified range.

val : It represents the item being sought within the specified range.

Return value

The function retrieves the count of appearances of the item 'val' within the interval [first, last).

Example 1

Example

#include<iostream>
#include<algorithm>
#include<vector>
using namespace  std;
int main()
{
	int newints[]={50,60,70,70,60,50,50,60};
	int newcount=std::count(newints, newints+8, 50);
	std::cout<<"50 appear "<<newcount<<"times.\n";
	std::vector<int> newvector(newints, newints+8);
	newcount=std::count(newvector.begin(),newvector.end(),70);
	std::cout<<"70 appear "<<newcount<<"times.\n";
	return 0;
}

Output:

Output

50 appear 3 times.
70 appear 2 times.

Example 2

Example

#include <bits/stdc++.h>
using namespace std;
int main()
{
	int ar[]={6,4,2,6,6,10,6};
	int n = sizeof(ar)/sizeof(ar[0]);
	cout<<"The number of times 6 appear is:"<<count(ar,ar+n,6);
	return 0;
}

Output:

Output

The number of times 6 appear is: 4

Complexity

The function's complexity increases linearly based on the distance between the initial and final elements.

Data races

Some or all of the components within the range are retrieved.

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