What is an Unordered_map?
At its core, std::unordered_map
is an associative container that maps unique keys to values using a hash table data structure. Unlike its counterpart std::map
, which maintains elements in sorted order, std::unordered_map
eshews ordering constraints, offering constant-time average complexity for key operations.
In simple terms:
Imagine you have a notebook where you want to keep track of information, but instead of writing everything down in order, you want to quickly find each piece of information based on a unique key. That's what an unordered_map
is like in C++.
Here's how it works:
- Key-Value Pairs: Each piece of information you want to store is called a "value", and you associate it with a unique "key". For example, you might have a key like "Name" and its associated value might be "John".
- Fast Lookup: Just like how you'd flip through your notebook to find information quickly based on the section headers or tabs, an
unordered_map
lets you find information super fast based on its unique key. - No Specific Order: The entries in your notebook are not necessarily in any particular order. You might have "Age" written down before "Name" or vice versa. Similarly, in an
unordered_map
, the key-value pairs are not sorted in any specific order. - Avoid Duplicate Keys: Each key in the map must be unique. If you try to add a new key that's the same as an existing one, it won't work - it's like trying to add another tab with the same name in your notebook.
Syntax
In order to use an unordered_map in C++, we first need to include the unordered_map
header file.
#include <unordered_map>
int main() {
std::unordered_map<KeyType, ValueType> myMap;
// Add key-value pairs, perform operations
return 0;
}
In this syntax:
KeyType
represents the type of keys you want to use.ValueType
represents the type of values associated with each key.myMap
is the name of theunordered_map
variable you are declaring.
Example:
unordered_map<int, int> unordered_map_integer;
Initializing: