Last Updated : 19 May, 2025
In C++, map and unordered_map are the containers that store can store data in the form of key-value pairs, but they differ significantly in terms of underlying implementation and performance characteristics.
The below table lists the primary differences between map and unordered_map container:
map
unordered_map
It stores key-value pairs in sorted order based on the key.
It is also storing key-value pairs but not in any specific order
It is implemented using red-black tree.
It is implemented using hash table.
It is slower for most operations due to sorting.
It is faster for most operations.
It takes O(log n) time for inserting, accessing, and deleting an element.
It takes O(1) average time for inserting, accessing, and deleting an element.
Let's discuss a bit about each of them.
MapThe C++ map container is ideal for situations where data needs to be stored in sorted order and when you need to efficiently access the predecessor or successor of a specific element.
Example:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
// Ordered map
std::map<int, int> order;
// Mapping values to keys
order[5] = 10;
order[3] = 500;
order[20] = 100;
order[1] = 1;
// Iterating the map and
// printing ordered values
for (auto i = order.begin(); i
!= order.end(); i++) {
cout << i->first
<< " : " << i->second
<< endl;
}
}
1 : 1 3 : 500 5 : 10 20 : 100Unordered Map
C++ unordered_map container is best suited for situations where fast access to elements is required, and the order of elements does not matter.
Example:
CPP
#include <bits/stdc++.h>
using namespace std;
int main() {
unordered_map<int, int> order;
// Mapping values to keys
order[5] = 10;
order[3] = 500;
order[20] = 100;
order[1] = 1;
// Iterating the map and
// printing unordered values
for (auto i = order.begin();
i != order.end(); i++){
cout << i->first
<< " : " << i->second
<< endl;
}
}
1 : 1 3 : 500 20 : 100 5 : 10
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4