Open In App

count() in C++ STL

Last Updated : 27 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, the count() is a built-in function used to find the number of occurrences of an element in the given range. This range can be any STL container or an array. In this article, we will learn about the count() function in C++.

Let’s take a quick look at a simple example that uses count() method:

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {2, 3, 2, 1, 5, 4, 2};

    // Count the occurrence of 2
    cout << count(v.begin(), v.end(), 2);
    return 0;
}

Output
3

This article covers the syntax, usage, and common examples of count() function in C++:

Syntax of count()

The count() function is defined inside the <algorithm> header file.

count(first, last, val);

Parameters

  • first: Iterator to the first element of the range.
  • last: Iterator to the element just after the last element of the range.
  • val: Value to be counted.

Return Value

  • If the value found, it returns the number of its occurrences.
  • Otherwise, it returns 0.

Examples of count()

The following examples demonstrates the use of count() function for different purposes:

Count of Given String in Vector of Strings

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<string> v = {"Hi", "Geeks", 
                        "GeeksforGeeks", 
                        "Geeks"};

    // Count the occurrence of "Geeks"
    cout << count(v.begin(), v.end(), "Geeks");
  
    return 0;
}

Output
2

Count the Frequency of Given Element in Multiset

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    multiset<int> m= {1, 1, 2, 3, 2, 2, 2, 1};
	
    // Counting the frequency of 2 
    cout << count(m.begin(), m.end(), 2);
  
    return 0;
}

Output
4

Note: Unique value containers such as set, maps, etc. can only return either 1 or 0 from the count function.

Check Whether the Given Element Exists

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {2, 3, 2, 1, 5, 4, 2};
  	int val = 7;
  
  	// Count the occurrence of 7
  	int c = count(v.begin(), v.end(), val);

    // Check if the element exists
    if (c)
      	cout << c;
    else
      	cout << val << " Not Exists";
  
    return 0;
}

Output
7 Not Exists


Next Article
Practice Tags :

Similar Reads