Prefer vector first
It is compact, cache-friendly, supports random access, and solves most sequence problems cleanly.
Implementation companion
Choose the right standard-library container, remember its guarantees, and avoid the C++ errors that make a correct algorithm fail in practice.
Need to install C++17 first?| Container | Model | Access / lookup | Insert / remove | Search | Choose it when… |
|---|---|---|---|---|---|
| array<T,N> | Fixed contiguous sequence | O(1) | — | O(n) | Size known at compile time |
| vector<T> | Dynamic contiguous sequence | O(1) | O(1) amortized | O(n) | Default sequence; excellent locality |
| deque<T> | Chunked double-ended sequence | O(1) | O(1) both ends | O(n) | Stable fast front and back growth |
| list<T> | Doubly linked list | O(n) | O(1) at known iterator | O(n) | Use only when iterator splicing matters |
| forward_list<T> | Singly linked list | O(n) | O(1) after iterator | O(n) | Lower link overhead; forward-only |
| stack<T> | LIFO adaptor | top O(1) | push/pop O(1) | O(n) | DFS, parsing, undo |
| queue<T> | FIFO adaptor | front O(1) | push/pop O(1) | O(n) | BFS and scheduling |
| priority_queue<T> | Binary heap adaptor | top O(1) | push/pop O(log n) | O(n) | Repeated min/max selection |
| set/map | Ordered balanced tree | O(log n) | O(log n) | O(log n) | Sorted traversal and worst-case bounds |
| unordered_set/map | Hash table | O(1) expected | O(1) expected | O(1) expected | Fast lookup without ordering |
Hash-container bounds are expected/amortized; adversarial collisions can make an operation O(n). Tree containers keep keys ordered and guarantee O(log n).
It is compact, cache-friendly, supports random access, and solves most sequence problems cleanly.
Indices make ownership simpler and serialize naturally; raw owning pointers demand explicit cleanup.
vector growth invalidates every iterator and pointer; erase invalidates positions at and after the erased item.
Use adaptors for restricted interfaces and direct containers when you need iteration.
C++ comparators express lower priority, which is why min-heaps often use >.
Warnings catch suspicious conversions; sanitizers expose memory and undefined-behaviour bugs.