C++ Unordered_map::count() Function



The C++ unordered_map::count()function is used to return the number of mapped values associated with keyk. This means this function only gives the values of 1 or 0 because the container does not allow duplicate keys and returns 1 if an element with that key exits the container and zero otherwise.

In other words, this container does not allow duplicate values, so the count() function always returns either 0 or 1.

Syntax

Following is the syntax of unordered_map::count() function

size_type count(const key_type& k) const;

Parameters

  • k − It indicates the count need to be returned in the unordered_map.

Return value

Returns 1 if container has value associated with key k otherwise 0.

Example 1

In the following example, let's look the basic usage of unordered_map::count() function, as follows:

#include <iostream>
#include <unordered_map>
using namespace std;
int main(void) {
   unordered_map<char, int> um = {
      {'a', 1},
      {'b', 2},
      {'c', 3},
      {'d', 4},
      {'e', 5}
   };
   if (um.count('a') == 1) {
      cout << "um['a'] = " << um.at('a') << endl;
   }
   if (um.count('z') == 0) {
      cout << "Value not present for key um['z']" << endl;
   }
   return 0;
}

Output

Following is the output of the above code −

um['a'] = 1
Value not present for key um['z']

Example 2

Consider the following example, where we are using theunordered_map::count() function to find whether an assigned key is available or not, as follows:

#include <iostream>
#include <unordered_map>
using namespace std;
int main(void) {
   unordered_map<char, int> um = {
      {'a', 1},
      {'b', 2},
      {'c', 3},
      {'d', 4},
      {'e', 5}
   };
   int count1 = um.count('b');
   cout<<"the count value of b is: "<<count1<<endl;
   int count2 = um.count('z');
   cout<<"the count value of z is: "<<count2;
   return 0;
}

Output

Output of the above code is as follows −

the count value of b is: 1
the count value of z is: 0

Example 3

Let's look at the following example, where we are using the unordered_map::count()function in the if condition to display their value associated with key k, as follows:

#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
int main () {
   unordered_map<int, string> Umap;
   Umap[1] = "tutorialspoint";
   Umap[2] = "Hyderabad India";
   Umap[3] = "Tutorix";
   Umap[4] = "Noida India";
   if(Umap.count(1)==1 && Umap.count(2)==1){
      cout<<Umap.at(1)<<" "<<Umap.at(2)<<endl;
   }
   return 0;
}

Output

If we run the above code it will generate the following output −

tutorialspoint Hyderabad India