Last Updated : 27 Nov, 2024
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;
}
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.
Parameterscount(first, last, val);
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;
}
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;
}
Check Whether the Given Element Exists C++Note: Unique value containers such as set, maps, etc. can only return either 1 or 0 from the count function.
#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;
}
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4