# map vs unordered_map, and choosing an STL container

> Compare std::map and std::unorderedmap (and set vs unorderedset). What are their complexities, and how do you choose among vector, list, deque, map and...

Canonical: https://www.internhack.in/learn/interview/cpp-interview/cpp-map-vs-unordered-map-containers
Last updated: 2026-11-28

Difficulty: Intermediate

## Question

Compare std::map and std::unordered_map (and set vs unordered_set). What are their complexities, and how do you choose among vector, list, deque, map and unordered_map?

## Answer

Picking the right container is a core skill, and this question tests whether you know not just Big-O but also what the containers are made of. Let's compare the two associative families first.

std::map (and std::set) is an ordered associative container, implemented as a self-balancing binary search tree, usually a red-black tree. Keys are kept sorted, so iteration gives you keys in ascending order. Insert, erase, and find are O(log n) guaranteed. It needs an ordering, by default operator<, or a custom comparator. std::unordered_map (and unordered_set) is a hash table: keys are hashed into buckets, so insert, find, and erase are O(1) on average, but degrade to O(n) in the worst case when many keys collide. Iteration order is unspecified. It needs a hash function and operator== for the key type, which is why using a pair or a custom struct as a key requires you to supply a hash. Think of map as a dictionary printed in alphabetical order, and unordered_map as a set of lockers where the key's hash tells you which locker to open.

How do you choose? Use unordered_map when you just need fast lookups and don't care about order, as in frequency counting or memoisation. Use map when you need sorted iteration, range queries (lower_bound, upper_bound), the smallest or largest key, or predictable worst-case performance. In adversarial settings, hash tables can be attacked with collisions. Also note that unordered_map has larger constant factors in memory (buckets and node allocations), and rehashing invalidates iterators, while map iterators stay valid across inserts.

A well-known gotcha is operator\[\]: on a map or unordered_map, m\[key\] inserts a default-constructed value if the key is absent. So using it in a read-only check silently grows your container. Use find() or count() (or contains() in C++20) to test presence, and at() to throw for a missing key. Use try_emplace or insert_or_assign for precise insertion semantics. Also, multimap and multiset allow duplicate keys.

For the sequence containers: vector is the default, with contiguous memory, O(1) random access, amortised O(1) push_back, and excellent cache behaviour. deque offers O(1) push and pop at both ends and O(1) random access, but with non-contiguous chunks, and is the backing store for std::queue and std::stack. list is a doubly linked list with O(1) insertion and erase anywhere given an iterator, but O(n) to find a position, no random access, and poor cache locality, so it rarely wins in practice. forward_list is the singly linked version. Bjarne Stroustrup's advice is famous: use vector unless you have a measured reason not to.

In interviews, mention the underlying structure, the complexities, and one gotcha (operator\[\] insertion, or iterator invalidation). That trio is what earns the full mark.

## Code examples

### Word count with map and unordered_map

```
#include <iostream>
#include <map>
#include <string>
#include <unordered_map>
#include <vector>

int main() {
    std::vector<std::string> words{"pear", "apple", "pear", "fig", "apple", "pear"};

    std::map<std::string, int> ordered;              // sorted by key
    std::unordered_map<std::string, int> hashed;     // no order guarantee
    for (const auto& w : words) { ++ordered[w]; ++hashed[w]; }

    for (const auto& [word, n] : ordered) std::cout << word << "=" << n << " ";
    std::cout << "\n";

    std::cout << hashed.at("pear") << "\n";
    std::cout << hashed.count("kiwi") << " " << hashed.size() << "\n";
    int x = hashed["kiwi"];        // operator[] INSERTS a default 0 value
    std::cout << x << " " << hashed.size() << "\n";
}
```

Iterating the map yields sorted keys. Calling count() does not insert, but operator\[\] on a missing key does, growing the map from 3 to 4 entries.

## Key points

- map/set: red-black tree, sorted, O(log n) operations; unordered_map/set: hash table, O(1) average, O(n) worst case.
- Unordered containers need a hash and equality; ordered ones need a strict weak ordering.
- operator\[\] inserts missing keys; use find, count, contains or at for lookups.
- vector is the default sequence container; deque for O(1) at both ends; list only when you need stable iterators and cheap splice.
- Rehashing invalidates unordered_map iterators; map iterators survive inserts.

## Common follow-up questions

- How would you use a pair<int,int> as an unordered_map key?
- What is a strict weak ordering?
- Why is std::list often slower than vector even for insert-heavy workloads?

## Interview tips

- Always state the underlying data structure, then the complexity.
- Mention the operator\[\] insertion trap unprompted.

## Concepts covered

std::map, std::unordered_map, std::set, complexity, container selection

Previous: [vector growth and iterator invalidation](https://www.internhack.in/learn/interview/cpp-interview/cpp-vector-growth-iterator-invalidation) · Next: [STL algorithms and priority_queue: sort, lower_bound, heaps](https://www.internhack.in/learn/interview/cpp-interview/cpp-stl-algorithms-priority-queue) · [All of C++ & STL](https://www.internhack.in/learn/interview/cpp-interview)

## More C++ & STL questions

- [Lambdas and capture modes](https://www.internhack.in/learn/interview/cpp-interview/cpp-lambdas-captures)
- [The static keyword and its different meanings](https://www.internhack.in/learn/interview/cpp-interview/cpp-static-keyword)
- [Undefined behaviour: common examples and how to avoid it](https://www.internhack.in/learn/interview/cpp-interview/cpp-undefined-behaviour)
- [Tricky C++ output questions](https://www.internhack.in/learn/interview/cpp-interview/cpp-tricky-output-questions)
- [What are the key differences between C and C++, and between struct and class?](https://www.internhack.in/learn/interview/cpp-interview/cpp-c-vs-cpp-struct-class)
- [References vs pointers in C++](https://www.internhack.in/learn/interview/cpp-interview/cpp-references-vs-pointers)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [C++ & STL](https://www.internhack.in/learn/interview/cpp-interview)
