unordered_map count() in C++

The unordered_map::count() is a builtin method in C++ which is used to count the number of elements present in an unordered_map with a given key.

Note: As unordered_map does not allow to store elements with duplicate keys, so the count() function basically checks if there exists an element in the unordered_map with a given key or not.

Syntax:



size_type count(Key);

Parameters: This function accepts a single parameter key which is needed to be checked in the given unordered_map container.

Return Value: This function returns 1 if there exists a value in the map with the given key, otherwise it returns 0.

Below programs illustrate the unordered_map::count() function:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to illustrate the 
// unordered_map::count() function
  
#include<iostream>
#include<unordered_map>
  
using namespace std;
  
int main()
{
    // unordered map
    unordered_map<int , string> umap;
      
    // Inserting elements into the map
    umap.insert(make_pair(1,"Welcome"));
    umap.insert(make_pair(2,"to"));
    umap.insert(make_pair(3,"GeeksforGeeks"));
      
    // Check if element with key 1 is present using 
    // count() function
    if(umap.count(1))
    {
        cout<<"Element Found"<<endl;
    }
    else
    {
        cout<<"Element Not Found"<<endl;    
    }
      
    return 0;
}

chevron_right


Output:

Element Found

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to illustrate the 
// unordered_map::count() function
  
#include<iostream>
#include<unordered_map>
  
using namespace std;
  
int main()
{
    // unordered map
    unordered_map<int , string> umap;
      
    // Inserting elements into the map
    umap.insert(make_pair(1,"Welcome"));
    umap.insert(make_pair(2,"to"));
    umap.insert(make_pair(3,"GeeksforGeeks"));
      
    // Try inserting element with
    // duplicate keys
    umap.insert(make_pair(3,"CS Portal"));
      
    // Print the count of values with key 3
    // to check if duplicate values are stored 
    // or not
    cout<<"Count of elements in map, mapped with key 3: "
            <<umap.count(3);
      
    return 0;
}

chevron_right


Output:

Count of elements in map, mapped with key 3: 1


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.