What is the difference between std::map and std::unordered_map?

Pointstd::mapstd::unordered_map
InsideBalanced treeHash table
OrderSorted by keyNo order
Find, insertO(log n)O(1) on average
Key needsoperator<hash and ==
IteratorsStay valid after insertCan be invalidated by a rehash
#include <iostream>
#include <map>
#include <string>
#include <unordered_map>

int main() {
    std::map<std::string, int> sorted{{"pear", 3}, {"apple", 1}, {"mango", 2}};
    for (const auto& [k, v] : sorted) std::cout << k << ' ';        // always sorted
    std::cout << '\n';

    std::unordered_map<std::string, int> fast{{"pear", 3}, {"apple", 1}};
    std::cout << fast.at("pear") << ' ' << fast.contains("kiwi") << '\n';
}
Output

apple mango pear
3 0

Choose unordered_map when you only look up by key. Choose map when you need the order or range searches. See STL Containers.


Learn more about the similar topics:
Tutorials
C++ Templates and Generic Programming
C++ STL Containers: map, set, unordered_map, queue and stack
C++ Algorithms and Iterators
Exercises & Assignments
Write a generic maximum template
Count the frequency of words with a map
Remove duplicates from a vector and keep the order
Interview Questions & Answers
What is the STL in C++?
What is the difference between std::map and std::unordered_map?
What is the difference between push_back and emplace_back in C++?
What is iterator invalidation in C++?
What is the difference between templates and macros in C++?