In this article we will discuss what is unordered_map and how it use it.
Unordered_map provides a functionality of map i.e. it store the elements in key value pair and with unique key only.
Unordered_map internally uses the hashing to achieve this. It internally uses a hash table to implement this hashing feature. If you want to know more about hashing check following article,
What is Hashing and Hash Table
In an unordered_map elements are stored in a key value pair combination. But elements are stored in arbitrary order unlike associative containers where elements were stored in sorted order of keys.
Let’s see an example by creating an unordered_map of string and int, to maintain the repeated count of a word i.e.
#include <iostream> #include <unordered_map> #include <string> int main() { // Create an empty unordered_map std::unordered_map<std::string, int> wordMap; // Insert Few elements in map wordMap.insert( { "First", 1 }); wordMap.insert( { "Second", 2 }); wordMap.insert( { "Third", 3 }); // Overwrite value of an element wordMap["Third"] = 8; // Iterate Over the unordered_map and display elements for (std::pair<std::string, int> element : wordMap) std::cout << element.first << " :: " << element.second << std::endl; return 0; }
Output:
Third :: 8 Second :: 2 First :: 1
As we can see above, elements are stored in arbitrary order.
The reason because unordered_map does the hashing i.e. whenever we try to insert an element in a unordered_map, it internally does the following steps,
Therefore, there is no specific order in which elements are stored internally.
The basic advantage of using unordered_map instead of associative map is the searching efficiency. In an unordered_map complexity to search for an element is O(1) if hash code are chosen efficiently.