5.2.19 · D3C++ Programming

Worked examples — STL containers — vector, list, deque, array, set, multiset, map, multimap, unordered_map, unordered_set

2,958 words13 min readBack to topic

The scenario matrix

Before any code, here is the full list of case classes container problems come in. Every worked example below is tagged with the cell it covers, and together they cover the whole table.

# Case class What makes it tricky Winning container Example
A Random access by index, read-heavy need v[i] vector / array Ex 1
B Insert/erase in the middle, many times shifting cost list Ex 2
C Insert at both ends (front + back) front push on vector is deque Ex 3
D Unique keys, fast lookup, order irrelevant hashing unordered_set/map Ex 4
E Keys must stay sorted / range queries tree ordering map / set Ex 5
F Duplicate keys must survive set drops dupes multiset / multimap Ex 6
G Degenerate / zero input (empty, size 0, single element) UB traps any — care needed Ex 7
H Limiting behaviour — capacity growth, worst-case collision amortised vs worst vector / unordered_map Ex 8
I Real-world word problem — pick from a paragraph translating needs → costs mixed Ex 9
J Exam twist — iterator invalidation / erase-during-loop silent dangling bug vector/map Ex 10
Recall Quick self-test before you read on

Which container for "front and back inserts, both cheap"? ::: deque Which containers keep unique keys and silently drop duplicates? ::: set and map both enforce unique keys (use multiset/multimap to keep duplicates) erase(value) on a multiset removes how many? ::: all matching copies


Cell A — Random access, read-heavy


Cell B — Insert/erase in the middle repeatedly

Figure — STL containers — vector, list, deque, array, set, multiset, map, multimap, unordered_map, unordered_set

Cell C — Insert at both ends

Figure — STL containers — vector, list, deque, array, set, multiset, map, multimap, unordered_map, unordered_set

Cell D — Fast lookup, order irrelevant


Cell E — Sorted keys / range queries


Cell F — Duplicates must survive


Cell G — Degenerate / zero input


Cell H — Limiting behaviour (capacity growth & worst case)

Figure — STL containers — vector, list, deque, array, set, multiset, map, multimap, unordered_map, unordered_set

Cell I — Real-world word problem


Cell J — Exam twist: iterator invalidation


Recall Final scenario check

Front + back cheap → ::: deque Sorted iteration for free → ::: map / set erase(it) returns → ::: a valid iterator to the next element Empty-vector front() → ::: undefined behaviour — guard with !empty()