Lesson 1310 min read
STL Containers
A fully-stocked kitchen β why build a pot from scratch when there's one on the shelf?
The Kitchen Analogy
The C++ Standard Template Library (STL) is like a professional kitchen that comes fully equipped. Need to store a list of items? There's a container for that. Need fast lookups by key? There's one for that too. Need a priority queue for scheduling? Already built.
The trick isn't learning every pot and pan β it's knowing which one to grab for the job.
Sequence Containers β Ordered Collections
These store elements in a specific order.
vectorβ Dynamic array. Your go-to default. Fast random access, fast append.dequeβ Double-ended queue. Fast insert/remove at both front and back.listβ Doubly-linked list. Fast insert/remove anywhere (if you have an iterator), but no random access.
Associative Containers β Key-Based Lookup
mapβ Sorted key-value pairs. \(O(\log n)\) lookup. Keys are ordered.setβ Sorted unique values. Like a map with no values.unordered_mapβ Hash table. \(O(1)\) average lookup. No ordering.unordered_setβ Hash set. Unique values, no ordering.
Container Adapters β Restricted Interfaces
stackβ LIFO. Push/pop from top only.queueβ FIFO. Push back, pop front.priority_queueβ Always pops the largest (or smallest) element first.
map β Word Frequency Counter
set β Unique Elements, Automatically Sorted
unordered_map vs. map β Performance
priority_queue β Top-K Elements
stack β Bracket Matching
When to Use Which?
| Need | Container | Why |
|---|---|---|
| General-purpose list | vector | Cache-friendly, fast random access |
| Fast front + back ops | deque | O(1) push/pop at both ends |
| Frequent mid-insert/remove | list | O(1) splice with iterator |
| Sorted key-value pairs | map | O(log n), ordered iteration |
| Fast key-value lookup | unordered_map | O(1) average |
| Unique sorted values | set | O(log n), auto-sorted |
| LIFO | stack | Push/pop top only |
| FIFO | queue | Push back, pop front |
| Always get max/min | priority_queue | Heap-based, O(log n) push/pop |
Note: unordered_map is O(1) average but O(n) worst case (hash collisions). map is O(log n) always. Use unordered_ versions when you don't need ordering β they're faster on average. But if you need sorted iteration or guaranteed worst-case performance, stick with map/set.
Challenge