std::count() function with example in C++ STL

C++ STL | std::count() function: Here, we are going to learn about the count() function in C++ STL with example.
Submitted by Yash Khandelwal, on April 30, 2019

C++ STL std:count() function

The C++ STL contains the function std::count(), which is used to find the occurrence of the particular element in the given range. You can use this function with an array, string, vector, etc.

To use this function, we have to use either <bits/stdc++> header or <algorithm> header.

Syntax of std::count() function:

    count( start_point , end_point , val/element);


  • start_point: from where we want to start searching or the initial position.
  • end_ point: ending point till where you want to search the element or the final position.
  • val/elements: value or the element to be searched.

Return value: It returns the numbers of occurrences of the element in the given range.

For example:

    If the given string is:

    Then if we count no of 'e's:
    count(str.begin(), str.end(), 'e');
    Output: 8


  • It throws exception when the element assignment is not proper or the iterator is out of range.
  • In case of invalid parameters shows the undefined behaviors.

Time Complexity:

O(n) is the time complexity of the std::count() function as it follows searching.

Input Output format:

    arr[] = { 3, 2, 1, 3, 3, 5, 3 };
    n = sizeof(arr) / sizeof(arr[0]);
    count(arr, arr + n, 3);


    str = "includehelp"; 
    count(str.begin(), str.end(), 'e'); 


C++ program to demonstrate example of std::count() function

	C++ program to count the number of occurences of
	particular element in array ,string, vector,etc.

using namespace std;

int main()
	//declaration of integer array arr
	int arr[]={2,3,5,3,5,6,3,5,5,5,5,4,5,3,6,7};
	int s =sizeof(arr)/sizeof(arr[0]);

	//declaration of vector container n
	vector<int> n={1,2,3,4,2,2,2,5,5,3,2,2,2,7,2};

	// take a string str
	string str ="anagramandanagram";

	//Here, we search the count of 5 in the array arr
	//you may change it also 2,3,6 wish
	cout << "Number of times 5 appears :";
	cout << count(arr, arr + s, 5);
	//Here, we search the count of 2 in the vector n
	//you may change it also 5,3,6... as wish
	cout << "\n\nNumber of times 2 appears : ";
	cout<<count(n.begin(), n.end(), 2);
	//Here, we search the count of 'a' in the string str
	//you may change it also b,c,d.. as wish	
	cout << "\n\nNumber of times 'a' appears : ";
	cout << count(str.begin(), str.end(), 'a');

	return 0;


Number of times 5 appears :7 
Number of times 2 appears : 8
Number of times 'a' appears : 7 

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.