C++ Data Structures and STL (DSA Core #11)
The STL is a set of containers plus the operations that are cheap on each one.
Almost every OA answer is a vector, a priority_queue, or an unordered_map,
and the difference between a passing and a failing solution is often one container
choice plus reserve.
vector, array, deque
vector is a dynamic array: contiguous, \(O(1)\) indexing, amortized \(O(1)\)
push_back.
vector<int> v = {3, 1, 4};
v.push_back(1); // amortized O(1)
v.reserve(1000); // allocate capacity once
v.size(); v.capacity(); v.empty();
v.front(); v.back();
v.insert(v.begin() + 1, 9); // O(n): shifts the tail
v.erase(v.begin()); // O(n)
reserve(n) is the cheapest optimization in the language: appending n elements
without it does \(\log n\) reallocations and copies, all of which reserve removes.
It changes capacity, not size. The total copying without reserve is still
linear, which is why push_back is amortized constant:
\[ 1 + 2 + 4 + \dots + n < 2n \]
but the constant and the peak memory are both better with one allocation.
array<int, 5> is a fixed-size array with no heap allocation and no size field.
Use it when the size is a compile-time constant:
array<int, 3> a = {1, 2, 3};
a.size(); // 3, a compile-time constant
deque is a segmented array with \(O(1)\) push/pop at both ends:
deque<int> d;
d.push_back(2);
d.push_front(1);
d.pop_front();
d[0]; // still O(1)
| Operation | vector |
deque |
array |
|---|---|---|---|
a[i] |
\(O(1)\) | \(O(1)\) | \(O(1)\) |
push_back |
amortized \(O(1)\) | \(O(1)\) | — |
push_front |
\(O(n)\) | \(O(1)\) | — |
| insert/erase middle | \(O(n)\) | \(O(n)\) | — |
| Memory | one block | blocks + map | inline |
Iterator invalidation is the trap:
vector: any reallocation invalidates all iterators, pointers, and references.reserveup front avoids it.deque:push_front/push_backinvalidate iterators but not references to existing elements.array: nothing invalidates.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
c/.style={draw, thick, minimum width=0.62cm, minimum height=0.55cm, font=\scriptsize\bfseries}]
\foreach \v [count=\i from 0] in {3,1,4,1} \node[c, fill=blue!10] at (\i*0.68,0) {\v};
\foreach \i in {4,...,7} \node[c, fill=gray!8] at (\i*0.68,0) {};
\draw[thick, orange] (-0.38,0.38) rectangle (2.6,0.38);
\draw[thick, orange] (-0.38,-0.38) rectangle (2.6,-0.38);
\node[font=\scriptsize, anchor=north] at (1.1,-0.55) {size = 4};
\node[font=\scriptsize, anchor=north] at (4.5,-0.55) {capacity = 8};
\end{tikzpicture}
resize and reserve?ASolution
resize(n) changes the number of elements (default-constructing new ones).
reserve(n) only changes capacity; size() is unchanged.
stack, queue, priority_queue
These are adapters: they restrict an underlying container to one access rule.
stack<int> st; st.push(1); st.top(); st.pop();
queue<int> q; q.push(1); q.front(); q.pop();
| Adapter | Operations | Default container |
|---|---|---|
stack |
push/pop/top, \(O(1)\) | deque |
queue |
push/pop/front/back, \(O(1)\) | deque |
priority_queue |
push/pop \(O(\log n)\), top \(O(1)\) | vector + heap |
priority_queue is a max-heap by default. For a min-heap, pass a comparator:
priority_queue<int> maxHeap;
priority_queue<int, vector<int>, greater<int>> minHeap;
For custom types, the comparator is the same strict-weak-ordering rule as sort:
struct Task { int priority, id; };
struct ByPriority {
bool operator()(const Task& a, const Task& b) const {
if (a.priority != b.priority) return a.priority > b.priority; // min
return a.id > b.id;
}
};
priority_queue<Task, vector<Task>, ByPriority> pq;
priority_queue has no decrease-key, no iteration, and no way to remove an
arbitrary element. Dijkstra works around it with stale-entry skipping; “remove
from the middle of a heap” needs a different structure or lazy deletion.
priority_queue’s comparator “reversed” compared to sort?ASolution
The comparator defines “a has lower priority than b”. The heap puts the element
with highest priority on top, so return a > b makes the smallest value the
top — a min-heap.
set, multiset, unordered_set
set is a red-black tree: sorted, \(O(\log n)\) for everything, stable iterators.
unordered_set is a hash table: average \(O(1)\), no order, iterators invalidated by
rehash.
set<int> s = {5, 1, 3};
s.insert(4);
s.erase(3);
s.count(5); // 0 or 1
s.find(5); // iterator or end()
auto it = s.lower_bound(2); // first element >= 2 (not in unordered_set)
multiset allows duplicates and is the structure for “sliding window with ordered
contents”, “k-th smallest with insertions”, and “find the closest value”:
multiset<int> ms = {4, 4, 7};
ms.erase(ms.find(4)); // erase ONE 4 (erase(4) removes all)
That difference is a classic bug: erase(key) removes every equal element,
erase(iterator) removes one.
For an ordered set of pairs, set<pair<int,int>> needs no custom hash and gives
lower_bound on the whole pair (first, then second).
\begin{tikzpicture}[font=\rmfamily, >=stealth,
n/.style={draw, thick, circle, minimum size=0.58cm, font=\scriptsize\bfseries},
a/.style={->, thick}]
\node[n, fill=blue!12] (r) at (0,0) {4};
\node[n] (l) at (-1.2,-0.85) {2};
\node[n] (rr) at (1.2,-0.85) {6};
\node[n] (ll) at (-1.8,-1.7) {1};
\node[n] (lr) at (-0.6,-1.7) {3};
\node[n] (rl) at (0.6,-1.7) {5};
\draw[a] (r) -- (l); \draw[a] (r) -- (rr);
\draw[a] (l) -- (ll); \draw[a] (l) -- (lr);
\draw[a] (rr) -- (rl);
\node[font=\scriptsize, anchor=west] at (1.9,-0.4) {inorder = sorted};
\end{tikzpicture}
unordered_set do lower_bound?ASolution
Hashing destroys order. There is no way to find the nearest key without scanning all buckets, so the operation is not offered.
map, multimap, unordered_map
Same split as sets, with values attached.
map<string,int> m;
m["a"]++; // inserts {"a", 0} then increments
m.count("a"); // 0 or 1
m.erase("a");
for (auto& [k, v] : m) ... // sorted by key
operator[] requires a default-constructible value and inserts on miss. That
makes it wrong for lookups in a const map and a hidden source of wrong answers:
if (m.find("x") != m.end()) use(m.at("x")); // read without inserting
multimap allows duplicate keys and has equal_range for all values of one key.
unordered_map trades order for speed and accepts a custom hash:
struct PairHash {
size_t operator()(const pair<int,int>& p) const {
static const uint64_t C = 0x9e3779b97f4a7c15ULL;
uint64_t h = (uint64_t)(uint32_t)p.first * C;
h ^= (uint64_t)(uint32_t)p.second + C + (h << 6) + (h >> 2);
return h;
}
};
unordered_map<pair<int,int>, int, PairHash> grid;
For adversarial inputs, unordered_map with the default hash can be forced into
\(O(n)\) per operation by colliding keys. A randomized or well-mixed custom hash
prevents the constructed worst case.
m["missing"] change the size of the map?ASolution
operator[] default-constructs the value when the key is absent, then returns a
reference to it. It is an insert operation, not a lookup.
Iterators
An iterator is a generalized pointer. The category determines which algorithms accept it:
| Category | Supports | Containers |
|---|---|---|
| Input | read once, ++ |
streams |
| Forward | read/write, ++ |
forward_list, unordered_* |
| Bidirectional | ++, -- |
list, set, map |
| Random access | +, -, [], compare |
vector, deque, array |
std::sort needs random access, which is why list has a member sort() and
set cannot be sorted at all (it already is).
for (auto it = v.begin(); it != v.end(); ++it) cout << *it;
for (int x : v) cout << x; // copy
for (int& x : v) x *= 2; // reference, modifies
for (const auto& p : m) cout << p.first;
Invalidation rules by container:
vector: reallocation kills everything.deque: push at either end kills iterators, references survive.list,set,map: insertions never invalidate; only erasing the element does.unordered_*: rehash invalidates iterators, references survive.
The erase-while-iterating idiom:
for (auto it = m.begin(); it != m.end(); ) {
if (bad(it->first)) it = m.erase(it); // erase returns the next iterator
else ++it;
}
m.erase(it) invalidates it, so ++it in the loop header would be
use-after-free.
for (int x : v) x *= 2; not modify the vector?ASolution
x is a copy. The range-for binds each element by value unless you write
int& x.
Custom comparators
Two ways: a functor struct or a lambda. Both must be a strict weak ordering:
irreflexive (cmp(a,a) false), transitive, and consistent for equivalent
elements.
// sort: descending by first, ascending by second
sort(v.begin(), v.end(), [](const auto& a, const auto& b) {
if (a.first != b.first) return a.first > b.first;
return a.second < b.second;
});
// as a named functor, usable by set/map/priority_queue
struct Cmp {
bool operator()(int a, int b) const { return a > b; }
};
set<int, Cmp> desc;
Rules that keep it correct:
- Never use
<=or>=; equality must returnfalse. - Break all ties with a deterministic field, or the order is unspecified.
- Capture nothing in the lambda for
set/mapcomparators (they are stored copies; capture-by-reference dangles). sortis not stable;stable_sortis.- For
map/set, the comparator defines key equality: two keys are equivalent when neither is less than the other.
// WRONG: crashes or produces garbage
sort(v.begin(), v.end(), [](int a, int b) { return a <= b; });
a <= b dangerous in a comparator?ASolution
For equal elements it claims both a < b and b < a, so the ordering is not
strict. The sort’s partitioning can then move an iterator past the end.
Sorting with custom comparison
sort(v.begin(), v.end()); // ascending, O(n log n)
sort(v.rbegin(), v.rend()); // descending
stable_sort(v.begin(), v.end(), cmp); // preserves ties
partial_sort(v.begin(), v.begin() + k, v.end()); // smallest k, O(n log k)
nth_element(v.begin(), v.begin() + k, v.end()); // k-th in O(n) avg
partial_sort and nth_element matter when the problem asks for “top k” or
“k-th largest” and \(k \ll n\): sorting everything is wasted work.
For pairs, the default sort is lexicographic, which is often exactly what you
want and saves a comparator. For structs, write the comparator or define
operator<.
struct Item { int w, v; };
sort(items.begin(), items.end(), [](const Item& a, const Item& b) {
return (long long)a.v * b.w > (long long)b.v * a.w; // value density
});
The long long cast matters: v * w can overflow 32 bits and silently reverse
the comparison.
stable_sort required rather than preferred?ASolution
When the result must preserve the input order of equal keys, for example sorting records by one field while keeping a previous sort’s order on another.
Complexity guarantees
| Container | Access | Insert | Erase | Find | Notes |
|---|---|---|---|---|---|
vector |
\(O(1)\) | \(O(1)\) back amortized | \(O(n)\) | \(O(n)\) | contiguous |
deque |
\(O(1)\) | \(O(1)\) both ends | \(O(n)\) middle | \(O(n)\) | segmented |
list |
\(O(n)\) | \(O(1)\) with iterator | \(O(1)\) with iterator | \(O(n)\) | node per element |
set/map |
\(O(\log n)\) | \(O(\log n)\) | \(O(\log n)\) | \(O(\log n)\) | red-black tree |
unordered_set/map |
— | avg \(O(1)\), worst \(O(n)\) | avg \(O(1)\) | avg \(O(1)\) | hash table |
stack/queue |
\(O(1)\) top/front | \(O(1)\) | \(O(1)\) | — | adapters |
priority_queue |
\(O(1)\) top | \(O(\log n)\) | \(O(\log n)\) | — | binary heap |
Two practical notes that the table hides:
- A
vectorscan is often 5–10× faster than alistscan at the same complexity, because of cache lines and prefetching. mapandsetallocate a node per element (about 48 bytes formap<int,int>), which makes them 3–5× more memory-hungry than a sorted vector of pairs.
unordered_map lookup is \(O(1)\) average. When is it worse thanmap’s \(O(\log n)\)?
ASolution
Under adversarial or badly distributed keys, chains grow and lookups degrade toward \(O(n)\). Also when iteration order matters or when the constant factor of hashing dominates for tiny maps.
Choosing a container
| Need | Container |
|---|---|
| Indexed access, iteration, default choice | vector |
| Fixed small size | array |
| Push/pop both ends, BFS with front pops | deque |
| LIFO, DFS, undo | stack |
| FIFO, BFS | queue |
| Repeated min/max, Dijkstra, top-k | priority_queue |
Sorted unique keys, lower_bound, range queries |
set / map |
| Duplicates with order | multiset / multimap |
| Point lookups, no order | unordered_set / unordered_map |
| \(O(1)\) splice with stable addresses | list (rare) |
OA habits that matter more than the container choice:
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n; cin >> n;
vector<int> a(n);
for (int& x : a) cin >> x;
vector<int> v;
v.reserve(n);
- Use
'\n', notendl(which flushes). - Read the constraint and pick the container: \(n = 10^5\) and \(O(n \log n)\) is fine; \(O(n^2)\) is not.
- Use
long longfor sums, products, and counts. - Prefer
int cnt[26]over a map for lowercase characters. unordered_mapneedsreservetoo when you know the size.- Do not use
mapjust to count frequencies; it costs a \(\log\) and an allocation per key.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=4pt, minimum width=3.1cm, minimum height=0.62cm, font=\scriptsize},
a/.style={->, thick}]
\node[b, fill=blue!10] (q) at (0,1.6) {need order or lower\_bound?};
\node[b, fill=green!18] (y) at (-1.9,0) {set / map};
\node[b, fill=orange!15] (n) at (1.9,0) {need only lookups?};
\node[b, fill=green!18] (h) at (1.9,-1.4) {unordered\_*};
\draw[a] (q) -- node[left, font=\tiny] {yes} (y);
\draw[a] (q) -- node[right, font=\tiny] {no} (n);
\draw[a] (n) -- node[right, font=\tiny] {yes} (h);
\end{tikzpicture}
What do you use?
ASolution
An order-statistic tree (GNU pb_ds) or a Fenwick tree over
compressed values. A multiset gives the k-th element only in \(O(n)\) by
iteration, which is usually too slow.
Bugs and edge cases
vector<bool>is a bit-packed specialization:operator[]returns a proxy, notbool&, soauto&and taking addresses fail. Usevector<char>instead.- Iterator invalidation.
push_backinside a loop over a vector can reallocate and invalidate the loop’s iterator. erasewhile iterating. Useit = c.erase(it).operator[]inserts. A read that grows the map is a logic bug waiting to surface as a wrong size.- Comparator non-strictness.
<=can crashsort. - Overflow in comparisons.
a.v * b.wwithintoverflows; cast tolong long. size()unsigned.v.size() - 1underflows on an empty vector.priority_queuemutation. Changing the value of the top element in place breaks the heap; pop and push.setwith mutable keys. Never modify a key through aconst_cast; erase and reinsert.reserveon the wrong container.listandmaphave noreserve.
unordered_map solution times out at \(n = 2 \cdot 10^5\) whilethe same code with map passes. Why?
ASolution
Either the judge has anti-hash tests that collide the default hash, or the map is
small enough that allocation dominates. Use a custom mixed hash and
reserve(n), or switch to a sorted vector plus binary search.
That is the end of the core series. The next step is problems: pick the pattern from the statement, say the complexity out loud, then write the code.