The std::map::count() in C++ is a built-in function that is used to count the occurrence of the given key in the map container. It is the member function of the std::map container.
In this article, we will learn how to use std::map::count() in C++.
Syntax
mp.count(key)
Parameters
- key: The value whose occurrence is to be searched.
Return Value
- Returns 1, if the key is present in the map container, as the key is always unique in the map.
- Returns 0, if the key is not present in the map.
Example of map::count()
// C++ Program to illustrate, how to use
// std::map::count for counting the occurrence
// of given key
#include <bits/stdc++.h>
using namespace std;
int main() {
map<int, int> mp;
mp.insert({2, 30});
mp.insert({1, 40});
mp.insert({3, 60});
mp.insert({4, 20});
mp.insert({5, 50});
int key1 = 1;
int key2 = 9;
// Counting the occurrence of key1 and key2
int cnt1 = mp.count(key1);
int cnt2 = mp.count(key2);
cout << "Count of " << key1 << ": " <<
cnt1 << endl;
cout << "Count of " << key2 << ": " <<
cnt2 << endl;
return 0;
}
Output
Count of 1: 1 Count of 9: 0
Time Complexity: O(log n), where n is the number of key in the map container.
Auxiliary Space: O(1)
Why map::count() exists?
std::map() container does not store the duplicate values, so why map::count() is needed as we can already check the existence of an element in a map using std::find() or map::find() functions.
Other containers such as multimap may contain more than one copy of the key. So the reason is that the containers in C++ STL are required to implement the count() function is to help in generic programming.