Course outline · 0% complete

0/27 lessons0%

Course overview →

pair, map, and unordered_map

lesson 9-1 · ~13 min · 24/27

Quiz

Warm-up from lesson 8-1: what happens when a std::vector grows past its current capacity?

If you take one interview tool from this course, make it the hash map. "Count occurrences" and "have I seen this before?" are the beating heart of hundreds of problems, and swapping a nested-loop O(n²) brute force for one map pass at O(n) (lesson 8-4) is the single most common optimization interviewers want to see.

pair: two values traveling together

#include <utility>
std::pair<std::string, int> p = {"alice", 30};
p.first    // "alice"
p.second   // 30

STL maps store their entries as pairs, so you will meet .first and .second constantly.

map and unordered_map: Python's dict, twice

#include <map>
std::map<std::string, int> age;
age["alice"] = 30;          // insert or overwrite
age["bob"]++;               // a missing key is inserted as 0, then incremented
age.count("alice")          // 1 if present, 0 if not
age.erase("bob");

for (const auto& kv : age)  // iterates in SORTED key order
    std::cout << kv.first << " " << kv.second << "\n";

std::map keeps keys sorted (a balanced tree underneath): lookup and insert cost O(log n) — the repeated-halving cost from lesson 8-4 — and iteration is ordered. std::unordered_map (a hash table, like dict) averages O(1) lookup but iterates in no useful order.

Rule of thumb: unordered_map for pure speed, map when you need sorted keys or predictable iteration.

One trap: age["carol"] on a missing key inserts carol with value 0. Check existence with .count(k) or .find(k) when you do not want that.

mdtbstd::map = sorted treeO(log n), ordered walkunordered_map = bucketskey, valkey, valhash picks the bucket, O(1) avg
map stores keys in a sorted tree, so iteration is ordered and operations cost O(log n). unordered_map hashes each key straight to a bucket for O(1) average lookups, with no ordering.

Code exercise · cpp

Run this word-frequency counter, the single most reused interview pattern. map keeps output alphabetical.

Quiz

You need the fastest possible average-case lookups by key and do not care about ordering. Which container?

Code exercise · cpp

Your turn. Read one word and print each distinct character with its count, in alphabetical order (a map<char, int> gives you that for free). Input is `hello`.

Code exercise · cpp

Your turn: build a character frequency map of "abracadabra", then print the counts for 'a', 'b', and 'r' separated by spaces. Expected: 5 2 2