Open In App

map vs unordered_map in C++

Last Updated : 19 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Map

The 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;
    }
}

Output
1 : 1
3 : 500
5 : 10
20 : 100

Unordered 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;
    }
}

Output
1 : 1
3 : 500
20 : 100
5 : 10

Next Article
Practice Tags :

Similar Reads