![]() |
VOOZH | about |
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:
3
The count() function is defined inside the <algorithm> header file.
count(first, last, val);
The following examples demonstrates the use of count() function for different purposes:
Example 1: Count of Given String in Vector of Strings
2
Explantion: count(v.begin(), v.end(), "Geeks") counts and prints the number of times "Geeks" appears in the vector v.
Example 2: Count the Frequency of Given Element in Multiset
4
Explanation: count(m.begin(), m.end(), 2) counts and prints how many times the value 2 appears in the multiset m.
Note: Unique value containers such as set, maps, etc. can only return either 1 or 0 from the count function.
Example 3: Check Whether the Given Element Exists
7 Not Exists
Explanation:It counts how many times the value 7 appears in the vector v and prints the count if present, otherwise prints "7 Not Exists".