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.
The count()
function accepts the following parameters:
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;}
l
in our vector and print the count.1
in our vector and print the count.10
in our array and print the count.In this way, we can easily use the count()
function in our coding solutions.