C++ Using STL Unordered Map Program
In this tutorial, we will learn about the concept of an Unordered Map in STL in the C++ programming language.
To understand the basic functionality of the Map Container in STL, we will recommend you to visit https://www.studytonight.com/cpp/stl/stl-container-map, where we have explained this concept in detail from scratch.
What is an Unordered Map?
It is the same as a Map except that it does not store the key-value pairs in sorted order of keys but stores them in random order.
For a better understanding of its implementation, refer to the well-commented C++ code given below.
using namespace std;
cout << "\n\nWelcome to Studytonight :-)\n\n\n";
cout << " ===== Program to demonstrate the working of an Unordered Map, in CPP ===== \n\n";
cout << "*** Each Element of a Map is a key value pair. *** \n\n";
cout << "*** When two elements having same key are inserted then only the latest copy is stored. *** \n\n";
cout << "*** An Unordered map internally uses a Hash Table to store the keys. *** \n\n";
//Unordered Map declaration (Map with key as integer and value as string)
unordered_map<int, string> m;
//Filling the elements by using the m[key]=value format.
cout << "\n\nFilling the Map with key-value pairs using the map[key]=value syntax."; //Unordered Map stores this in a random order
m = "Three";
m = "Four";
m = "One";
m = "Twenty";
m = "Thirty One";
m = "Four";
cout << "\n\nThe number of elements in the Unordered Map are: " << m.size();
cout << "\n\nThe elements of the Unordered Map stored using the Hash Table are: \n\n";
unordered_map<int, string>::iterator i;
int j = 0;
for (i = m.begin(); i != m.end(); i++)
cout << "\n Key number " << ++j << " is: " << i->first << " and its values is: " << i->second;
cout << "\n\nNote that only the latest copy with key 3 is stored with value four.";
cout << "\n\n\n";
We hope that this post helped you develop a better understanding of the concept of an Unordered Map Container in STL and its implementation in C++. For any query, feel free to reach out to us via the comments section down below.
Keep Learning : )