Skip to content

Module 8 · The Standard Template Library — topic 5 of 7

Maps (std::map and std::unordered_map)

Key–value storage: sorted std::map versus hashed std::unordered_map, insert/find/erase, the operator[] trap, counting frequencies and iterating in order.

Beginner 14 min read·Lesson 35 of 40 in C++ Programming

Learning objectives

  • Insert, look up and erase entries safely
  • Choose between map and unordered_map
  • Count frequencies and iterate in sorted order

Definition

std::map is an associative container of unique keys kept in sorted order (typically a red-black tree, O(log n) operations); std::unordered_map stores keys in a hash table with average O(1) operations and no ordering.

Introduction

A map answers “what is the value for this key?” — a phone book, a word count, a cache. C++ offers two: std::map keeps keys sorted, std::unordered_map uses hashing for faster average lookup.

Why it matters

Maps appear in almost every real program and many interview problems (two-sum, anagrams, frequency counts).

Misusing operator[] for lookups silently inserts keys — a common bug.

Detailed explanation

m[key] returns a reference, inserting a default value if the key is missing. Use it to write or to count (++m[word]).

For lookups use find (returns end() if absent), count/contains (C++20) or at (throws if absent).

insert({k, v}) doesn't overwrite an existing key; insert_or_assign (C++17) does; try_emplace constructs only if absent.

Iterating a map visits keys in ascending order; unordered_map order is unspecified.

Custom key types need operator< for map, or a hash and == for unordered_map.

Syntax

C++
std::map<std::string, int> stock;
stock["pen"] = 40;
stock.insert({"book", 12});
if (auto it = stock.find("pen"); it != stock.end()) std::cout << it->second;
stock.erase("book");
for (const auto& [item, qty] : stock) { /* sorted by item */ }
  • Elements are std::pair<const Key, Value>.
  • it->first is the key, it->second the value.
  • Keys can't be modified in place.

Code examples

Counting with operator[]

C++
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> votes;
for (std::string v : {"c", "python", "c", "java", "python", "c"}) ++votes[v];
for (const auto& [lang, n] : votes) std::cout << lang << ' ' << n << '\n';
return 0;
}
Output
c 3
java 1
python 2

Safe lookup

C++
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> price{{"pen", 10}, {"book", 250}};
for (std::string item : {"book", "bag"}) {
auto it = price.find(item);
if (it != price.end()) std::cout << item << ": " << it->second << '\n';
else std::cout << item << ": not found\n";
}
std::cout << price.size() << " items\n";
return 0;
}
Output
book: 250
bag: not found
2 items

More examples

Grouping anagrams with unordered_map

C++
#include <algorithm>
#include <iostream>
#include <map>
#include <string>
#include <unordered_map>
#include <vector>
int main() {
std::vector<std::string> words{"listen", "silent", "enlist", "google", "gogole", "cat", "act"};
std::unordered_map<std::string, std::vector<std::string>> groups;
for (const auto& w : words) {
std::string key = w;
std::sort(key.begin(), key.end());
groups[key].push_back(w);
}
std::map<std::string, std::vector<std::string>> ordered(groups.begin(), groups.end()); // sort for stable output
for (const auto& [key, list] : ordered) {
std::cout << key << ':';
for (const auto& w : list) std::cout << ' ' << w;
std::cout << '\n';
}
std::map<std::string, int> m{{"x", 1}};
m.insert({"x", 99}); // no overwrite
std::cout << m["x"] << ' ';
m.insert_or_assign("x", 99); // overwrite
std::cout << m["x"] << '\n';
return 0;
}
Output
act: cat act
eggloo: google gogole
eilnst: listen silent enlist
1 99

Step-by-step explanation

  • Sorting a word's letters gives a key shared by all its anagrams.
  • groups[key] creates an empty vector the first time and appends to it.
  • Copying into a std::map sorts the groups so output is deterministic.
  • insert keeps the existing value; insert_or_assign replaces it.

Expected output

Running “Grouping anagrams with unordered_map” prints exactly:

TextOutput
act: cat act
eggloo: google gogole
eilnst: listen silent enlist
1 99

Practical applications

  • Caches map keys to computed results.
  • Routers map addresses to handlers.
  • Compilers map identifiers to symbols.

Best practices

  • Use find/contains/at for lookups.
  • Use unordered_map for speed and map when order matters.
  • Reserve buckets for large unordered_maps.

Common mistakes

Lookup with operator[] inserts

Avoid

if (m["bag"] == 0) std::cout << "missing"; // now "bag" exists

Prefer

if (!m.count("bag")) std::cout << "missing";

operator[] creates the key with a default value.

Relying on unordered_map order

Avoid

for (auto& [k, v] : um) std::cout << k; // expecting sorted output

Prefer

std::map<K, V> sorted(um.begin(), um.end());

Hash table order is unspecified and can change between runs and compilers.

Important notes

  • operator[] requires a default-constructible value type and can't be used on a const map.
  • unordered_map worst case is O(n) with many collisions.

Key takeaways

  • map is sorted (O(log n)); unordered_map is hashed (O(1) average).
  • [] inserts missing keys; find doesn't.
  • Iterate maps with structured bindings.

Try it yourself

  1. 1
    Solve two-sum: find two indices whose values add up to a target using an unordered_map.
  2. 2
    Build a phone book with add, find and delete commands.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

7 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhat does `m["missing"]` do on a std::map<std::string, int> when the key is absent?
  • ModerateWhat is printed?
Practise this topic