Algorithm Count Function

C++ Algorithm countfunction accepts 'val' as argument and compares for the occurrence of element 'val' in the range. The number of occurrence of that element is returned.

Syntax

Example

template <class InputIterator, class T>

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

Parameter

first : It is an input iterator to the first element in the range.

last : It is an input iterator to the last element in the range.

val : It is the element whose occurrence is being searched in the range.

Return value

The function returns the number of occurrence of the element 'val' in the range [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 complexity of the function is linear up to a distance between first and last element.

Data races

Some or all of the elements of the range are accessed

Exceptions

The function throws an exception if any of the argument throws one.

Input Required

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