Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
communitycreator

How to use the count() function in C++

Harsh Jain

The count() function is available in the algorithm.h header file in C++. This function is used to get the number of appearances of an element in the specified range.

For example, if you want to find how many times 10 appears in the array [10,20,50,30,10,10,50,20,10], you can use the count() function instead of writing a loop to iterate over all the elements and then get the result.

Parameters

The count() 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.
  • val: This is the value that we are going to check for in the array and get its count.

Return

The count() function returns the number of appearances of the val in the range [first, last).

Let’s take a look at the code:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main() {
  vector<char> vec_char = {'h','e','l','l','o','w','o','r','l','d'};
  vector<int> vec_int = {1,4,7,8,2,3,1,5,6,21,1,35,1,3};
  int arr[] = {10,20,30,50,10,20,50,10,50,10};
  
  char ch = 'l';
  int count_vec_char = count(vec_char.begin(), vec_char.end(), ch);
  cout << "Number of " << ch << ": " << count_vec_char << endl;

  int num = 1;
  int count_vec_int = count(vec_int.begin(), vec_int.end(), num);
  cout << "Number of " << num << ": " << count_vec_int << endl;
  
  int number = 10;
  int size = sizeof(arr)/sizeof(int);
  int count_arr = count(arr, arr + size, number);
  cout << "Number of " << number << ": " << count_arr << endl;

  return 0;
}
Use count() function in C++

Explanation:

  • From lines 1 to 3, we import the required library.
  • From lines 7 to 9, we create three different arrays/vectors that store character and integer data.
  • In lines 12 and 13, we find the number of occurrences of character l in our vector and print the count.
  • In lines 16 and 17, we find the number of occurrences of integer 1 in our vector and print the count.
  • In lines 21 and 22, we find the number of occurrences of integer 10 in our array and print the count.

In this way, we can easily use the count() function in our coding solutions.

RELATED TAGS

c++
communitycreator
RELATED COURSES

View all Courses

Keep Exploring