Interview Q&A · C++ · 12 questions in this topic
STL Containers & Iterators — C++ Interview Q&A
The containers interviewers probe — vector, map, unordered_map, set, and iterator invalidation rules. Part of STL Containers & Algorithms · 213 questions in the C++ bank.
What is the STL and what are its three pillars?
Answer
The Standard Template Library (the containers/algorithms/iterators part of the C++ standard library) provides generic, composable components: containers own data (vector, map, set), iterators abstract positions and traversal, algorithms operate on iterator ranges (sort, find, transform).
Ranges (C++20) modernize this into views and constrained algorithms over whole ranges instead of iterator pairs.
Key points
- 1Containers — own and store elements.
- 2Iterators — generalize pointers to positions.
- 3Algorithms — generic operations over ranges.
Example
#include <vector> #include <algorithm> std::vector<int> v{3, 1, 2}; std::sort(v.begin(), v.end()); // algorithm + iterators + container
Why is `std::vector` the default container?
Answer
Vector stores elements contiguously: cache-friendly iteration, O(1) indexing, tiny constant factors, amortized O(1) push_back, and full compatibility with C APIs via data(). Most workloads are iterate-and-index heavy, where contiguity beats node-based structures despite O(n) insertion in the middle.
Reserve upfront when the size is known to avoid reallocations and invalidation.
Example
std::vector<int> v; v.reserve(1000); // one allocation, no growth invalidation v.push_back(1); // amortized O(1)
💡 Contiguous plus cache-friendly is the two-word justification; reserve() is the senior follow-through.
What is the difference between `size`, `capacity`, `reserve` and `resize`?
Answer
size is the live element count; capacity is allocated slots. reserve(n) grows capacity without creating elements (no size change). resize(n) changes size — constructing or destroying elements.operator[]/at address [0, size); [size, capacity) is allocated but objectless.
Shrinking never happens automatically; shrink_to_fit() is a non-binding request.
Example
std::vector<int> v{1, 2}; v.reserve(100); // size 2, capacity >= 100 v.resize(5); // size 5 (new zeros), capacity >= 5 // v[3] now valid; before resize it was UB
What invalidates vector iterators, pointers and references?
Answer
Reallocation (growth past capacity) invalidates everything. insert/erase invalidate at and after the point (and everything on reallocation). push_back invalidates everything if it reallocates, else only end(). reserve() up front, or index-based loops, are the standard defenses.
After invalidation, even comparing the old iterator is undefined — refresh it from the return value of insert/erase.
Example
std::vector<int> v = {1, 2, 3}; int* p = &v[0]; v.push_back(4); // p may dangle now (possible realloc) // refresh: p = &v[0];
`std::map` vs `std::unordered_map` — how do you choose?
Answer
map is an ordered tree (usually red-black): O(log n) ops, sorted iteration, heterogeneous lookup in C++14+. unordered_map is a hash table: average O(1), no ordering, needs a good hash, worst case degrades, and rehash invalidates iterators.
Choose map for ordering/range queries and deterministic iteration; unordered_map for pure key lookup speed with a quality hash.
Key points
- 1Ordering — map sorted, unordered_map unspecified.
- 2Complexity — map O(log n), unordered_map average O(1).
- 3Hash — unordered_map needs hash + equality; map needs ordering.
Example
#include <map> #include <unordered_map> std::map<int,int> ordered; // iterates sorted by key std::unordered_map<int,int> fast; // iterates arbitrarily
💡 Ask about iteration order needs first — that single question usually decides the container.
What is the difference between `set`, `multiset`, `unordered_set` and `map`?
Answer
set stores unique sorted keys; multiset allows duplicates sorted; unordered_set stores unique keys hashed (no order); map stores key-value pairs instead of bare keys. All associative containers expose find/count/lower_bound families; only ordered ones expose ordering operations.
Membership testing is the set use case; key-to-value association is the map use case.
Example
std::set<int> s{3, 1, 3}; // {1, 3}: unique + sorted std::multiset<int> ms{3, 1, 3}; // {1, 3, 3}: duplicates kept
What are iterators and what are their categories?
Answer
Iterators generalize pointers: they traverse containers without exposing representation. Categories form a hierarchy — input/output (single-pass), forward (multi-pass), bidirectional (+ backward), random-access (+ jumping/indexing), contiguous (C++20: physically adjacent).
Algorithms require minimum categories (sort needs random-access; C++20 ranges relax some of this), and each container documents its strongest guarantee.
Example
std::vector<int> v{1,2,3}; auto it = v.begin(); // random-access: it += 2 works // std::list has bidirectional only: no it += 2
💡 Name the five categories in order — interviewers often just want the ladder recited correctly.
What is the difference between `begin/end`, `cbegin/cend`, `rbegin/rend`?
Answer
begin/end delimit the mutable range; cbegin/cend force const iterators (read-only even from a non-const container); rbegin/rend traverse reversed (rbegin is the last element, rend is before-first). const member functions return const iterators from begin/end automatically.
Prefer cbegin/cend in generic read-only code to get const enforcement regardless of container constness.
Example
std::vector<int> v{1, 2, 3}; for (auto it = v.rbegin(); it != v.rend(); ++it) { /* 3,2,1 */ } // *v.cbegin() = 9; // error: read-only
Which operations invalidate iterators for each major container?
Answer
vector/deque/string: reallocation or middle insert/erase invalidate (deque also on ends for pointers). list/forward_list/associative (map/set) and unordered (on rehash only): iterators stay valid across insert; erase invalidates only the erased. Rule of thumb: node-based containers preserve iterators; contiguous ones do not.
Always refresh from insert/erase return values and re-lookup after reserve-changing operations.
Key points
- 1vector/string — reallocation kills everything.
- 2deque — ends are cheap, middles invalidate.
- 3list/map/set — only erased iterators die; unordered adds rehash.
💡 Node-based preserves, contiguous invalidates — one sentence covers 90% of invalidation questions.
`std::list` vs `std::vector` vs `std::deque` — when is each right?
Answer
vector wins by default (contiguous, cache-friendly). deque wins for O(1) push/pop at both ends with segmented storage and no reallocation moves. list wins only when iterator stability across splices plus O(1) middle insertion with an existing iterator matters — its pointer-chasing usually loses to vector even for insertions due to cache effects.
Measure before choosing list; experts are famously skeptical of default list usage.
Example
std::deque<int> dq; dq.push_front(1); dq.push_back(2); // both O(1), no reallocation
💡 Default vector, both-ends deque, stable-iterators list — the selection mantra.
What are `std::array`, `std::pair` and `std::tuple` for?
Answer
array is a fixed-size contiguous sequence with bound-checked at(), no overhead over C arrays, and proper value semantics. pair bundles two heterogenous values (the map element type); tuple generalizes to N values with structured bindings for unpacking.
Prefer array over C arrays always, and structured bindings (auto [a, b] = ...) over .first/.second spelling.
Example
#include <array> #include <tuple> std::array<int, 3> a{1, 2, 3}; // fixed, contiguous, safe std::tuple<int, std::string> t{1, "x"}; auto [n, s] = t; // structured binding
How do you erase elements from a container while iterating?
Answer
Use the erase return value: for sequence containers, it = c.erase(it) yields the next valid iterator; for associative containers, erase(it++) or (C++17) node handles work. Or use the erase-remove idiom for vectors (remove compacts, erase truncates). Never use a range-for with in-loop erasure on the same container.
C++20 adds std::erase/std::erase_if non-member helpers that do this correctly in one call.
Example
std::vector<int> v{1, 2, 3, 4}; // erase-remove idiom: v.erase(std::remove_if(v.begin(), v.end(), [](int x) { return x % 2 == 0; }), v.end()); // manual loop: for (auto it = v.begin(); it != v.end(); ) { it = (*it < 0) ? v.erase(it) : std::next(it); }
Recommended resourcesAffiliate links · may earn us a commission