01 / 21
{K} V "id" 42

std::map &
unordered_map

Master C++ key-value containers: when to choose sorted trees vs. hash tables, how to insert, lookup, and iterate, and the complexity trade-offs that matter in real code.

C++

What Is a Key-Value Container?

A key-value container stores data as pairs: every element has a unique key that maps to a value. Think of a dictionary: the word (key) points to its definition (value). In C++, the Standard Library provides two primary associative containers for this pattern.

std::map
Keeps keys in sorted order using a balanced binary search tree (red-black tree).
std::unordered_map
Stores keys in no particular order using a hash table for fast average-case access.

Why Key-Value Storage Matters

Without associative containers, you would need to search through arrays or vectors linearly: \( O(n) \) per lookup. Key-value containers let you jump directly to the data you need.

1
Fast lookups: Find a student's grade by their ID, not by scanning every record.
2
Unique keys: Each key appears at most once: no accidental duplicates.
3
Natural modelling: Phonebook, config settings, word frequency: the real world is full of key-value relationships.

Under the Hood: Tree vs. Hash Table

std::map (BST) "dog" "cat" "fox" "ant" "cow" Keys stored in sorted order O(log n) lookup std::unordered_map (Hash Table) [0] "fox" → 3 [1] "ant" → 5 [2] empty [3] "dog" → 7 → "cat" → 2 [4] "cow" → 1 Keys hashed into buckets O(1) average lookup

Declaring a Map

#include <map> #include <unordered_map> #include <string> // Sorted map: string keys → int values std::map<std::string, int> ages; // Hash map: string keys → int values std::unordered_map<std::string, int> scores;

Core Operations

std::map<std::string, int> m; // INSERT m["alice"] = 95; // operator[] m.insert({"bob", 88}); // insert pair // LOOKUP int score = m["alice"]; // 95 auto it = m.find("charlie"); // returns m.end() if missing // CHECK EXISTENCE if (m.count("bob")) // 1 = found, 0 = not // ERASE m.erase("bob"); // remove by key // SIZE m.size(); // number of pairs

Complexity at a Glance

std::map std::unordered_map
Insert \( O(\log n) \) \( O(1) \) avg
Lookup \( O(\log n) \) \( O(1) \) avg
Erase \( O(\log n) \) \( O(1) \) avg
Ordered iteration ✓ yes ✕ no
Worst-case lookup \( O(\log n) \) \( O(n) \)
Underlying structure Red-black tree Hash table

operator[] vs. find()

m["key"]
If the key doesn't exist, it inserts a default-constructed value (e.g., 0 for int). Convenient but can create unintended entries.
m.find("key")
Returns an iterator. If the key is missing, returns m.end(). Never modifies the map: safe for read-only checks.
// DANGER: creates "charlie" with value 0 int x = m["charlie"]; // m.size() just grew! // SAFE: does not modify the map auto it = m.find("charlie"); if (it != m.end()) { int x = it->second; }

Iterating Over a Map

std::map<std::string, int> grades = { {"Bob", 88}, {"Eve", 72}, {"Alice", 95} }; // Range-based for (C++11+) for (const auto& [name, grade] : grades) { std::cout << name << ": " << grade << "\n"; } // Output (sorted!): Alice: 95, Bob: 88, Eve: 72

How to Apply: Step by Step

1
Choose your container: Need sorted keys or guaranteed worst-case? Use std::map. Need raw speed? Use std::unordered_map.
2
Include the header: <map> or <unordered_map>.
3
Declare with types: map<KeyType, ValueType> name;
4
Insert data: Use operator[] for insert-or-update, or .insert() for insert-if-absent.
5
Access safely: Prefer .find() + iterator check to avoid accidental default insertions.

Example 1: Word Counter

Count how many times each word appears in a list. Use operator[] to auto-initialise counts to 0.

#include <unordered_map> #include <vector> #include <string> #include <iostream> int main() { std::vector<std::string> words = {"the", "cat", "sat", "on", "the", "mat"}; std::unordered_map<std::string, int> freq; for (const auto& w : words) freq[w]++; // auto-creates key with 0, then increments for (const auto& [word, cnt] : freq) std::cout << word << ": " << cnt << "\n"; }

Example 2: Sorted Phonebook

Store contacts and print them alphabetically. Here std::map is the right choice because we need sorted output.

#include <map> #include <string> #include <iostream> int main() { std::map<std::string, std::string> phone; phone["Eve"] = "555-1234"; phone["Alice"] = "555-5678"; phone["Bob"] = "555-0000"; // Iteration is always A → B → E (sorted!) for (const auto& [name, num] : phone) std::cout << name << ": " << num << "\n"; }

Example 3: Safe Lookup Pattern

Check if a student exists without modifying the map. This is the safest general pattern for read access.

std::map<std::string, int> grades = { {"Alice", 95}, {"Bob", 88} }; std::string target = "Charlie"; auto it = grades.find(target); if (it != grades.end()) { std::cout << target << " scored " << it->second << "\n"; } else { std::cout << target << " not found\n"; } // Output: Charlie not found // grades.size() is still 2 — no side-effects!

insert() vs. operator[]

std::map<std::string, int> m; m["x"] = 10; // inserts {"x", 10} m["x"] = 20; // OVERWRITES → {"x", 20} m.insert({"y", 30}); // inserts {"y", 30} m.insert({"y", 40}); // DOES NOTHING — "y" already exists // m["y"] is still 30
operator[]
Insert or overwrite. If the key exists, replaces the value. Useful for "set this key to this value no matter what."
insert()
Insert if absent. If the key exists, does nothing. Returns a pair with a bool indicating success.

Common Mistakes

✕ Accidental Insertion
Using m["key"] to check existence actually creates the key with a default value. Use find() or count() instead.
✕ Wrong Header
Including <map> does not give you unordered_map. Each container has its own header.
✕ Unhashable Key
Using a custom class as a key in unordered_map without providing a hash function causes a compile error.

Summary: map vs. unordered_map

std::map std::unordered_map
Header <map> <unordered_map>
Order Sorted by key Unordered
Avg. access \( O(\log n) \) \( O(1) \)
Worst-case access \( O(\log n) \) \( O(n) \)
Key requirement operator< std::hash + operator==
Memory Lower overhead Higher (hash buckets)
Best for Sorted output, range queries Maximum speed, no order needed

Question 1 of 5

What is the average time complexity for looking up a key in std::unordered_map?

Question 2 of 5

Given std::map<std::string, int> m; what does m["test"] return if "test" is not in the map?

Question 3 of 5

Which container should you choose if you need to iterate over keys in alphabetical order?

Question 4 of 5

What is the correct way to check if a key exists in a map without modifying it?

Question 5 of 5

What is the value of m["a"] after all three lines execute?