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
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.