Home »
C++ STL
unordered_map in C++ STL
C++ STL | unordered_map: In this tutorial, we will learn about the unordered_map container, its usages, declaration syntax, examples and its functions.
By Shivang Yadav Last updated : December 11, 2023
C++ unordered_map
The unordered_map in the C++ programming language is used to store data in the form of key and value pairs. In this map, the keys are unique values and are mapped to a value. These keys can be used to identify the elements of the structure uniquely.
There is no restriction on the data type of the key and value elements i.e. it can be of any user-defined of a predefined type.
Declaration Syntax
unordered_map <keyDataType, ValueDataType> map_name;
The map needs the data type of both key-value when it is initialized, both key-value can have a different datatype.
- The Key values are generally unique and precise which point to the values.
- The values can be duplicated.
Internal working of C++ unordered_map
The unordered_maps are internally implemented in the c++ programming language using a hash table. The keys are hashed into the hash table and mapped to the values using a hashing function.
- The values of unordered_map are not arranged in a specific order i.e. the keys are unordered.
Example of unordered_map in C++ STL
Now, let's see the working of the unordered_map with a program's help,
#include <iostream>
#include <unordered_map>
using namespace std;
int main()
{
unordered_map<char, string> myMap;
myMap['P'] = "Python";
myMap['S'] = "Scala";
myMap['C'] = "C++";
myMap['J'] = "JavaScript";
cout << "The elements of unordered_map are " << endl;
for (auto x : myMap)
cout << x.first << "\t" << x.second << endl;
}
Output:
The elements of unordered_map are
J JavaScript
S Scala
C C++
P Python
The unordered_map library in C++ contains multiple functions which support the functioning of the structure. It also has some built-in functions that allow the easy working of the unordered_map. Tasks like iteration, operations, etc can be performed easily using the built-in functions.
Comparison between unordered_map and other similar structures
- unordered_map Vs unordered_set:
Both are unordered structures, but the set does not contain key-value pairs there are many situations requiring unique elements.
- unordered_maps us map:
Both structures have a different internal implementation, the maps are implemented using a balanced tree structure clear as the unordered_map are implemented using a hash table.
C++ unordered_map Functions