C++ Unordered_map::size() Function



The C++ std::unordered_map::size() function is used to return the number of elements present in the unordered_map. If the unordered_map does not contain any element then size() function returns 0.

Syntax

Following is the syntax of std::unordered_map::size() function.

size_type size() const noexcept;

Parameters

This function does not accepts any parameter.

Return value

This function returns the actual number of element preset in the unordered_map's container.

Example 1

In the following example, let's demonstrate the usage of the unordered_map::size() function.

#include <iostream>
#include <unordered_map>
using namespace std;
int main(void) {
   unordered_map<char, int> um;
   cout << "Initial size of unordered map = " << um.size() << endl;
   um = {
      {'a', 1},
      {'b', 2},
      {'c', 3},
      {'d', 4},
      {'e', 5}
   };
   cout << "Size of unordered map after inserting elements = " << um.size() << endl;
   return 0;
}

Output

Let us compile and run the above program, this will produce the following result −

Initial size of unordered map = 0
Size of unordered map after inserting elements = 5

Example 2

Following is the example, where we are going to create a unordered_map that stores key-value pairs of integer types and applying the size() function to get how many elements are present in the current unordered_map.

#include <unordered_map>
#include <iostream>
using namespace std;
int main() { 
   unordered_map<int,int> nums {{1, 10}, {3, 30}, {5, 50}, {7, 70}};
   cout << "nums contains " << nums.size() << " elements.\n";
}

Output

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

nums contains 4 elements.

Example 3

Let's look at the following example, where we are going to find the even keys along with their values, storing them in another container, and applying the size() function to find the no.of elements.

#include <unordered_map>
#include <iostream>
using namespace std;
int main() { 
   unordered_map<int,int> uMap {{1, 5}, {2, 30}, {3, 50}, {4, 70}, {5, 10}, {6, 20}};
   unordered_map <int, int> nums;
   for(auto & it:uMap){
      if(it.first % 2 == 0){
         nums.insert({it.first, it.second});
      }
   }
   cout<<"total even key in nums unordered_map: "<<nums.size()<<endl;
   return 0;
}

Output

Following is the output of the above code −

total even key in nums unordered_map: 3
Advertisements