Interview Q&A · C++ · 12 questions in this topic

STL Containers & Iterators — C++ Interview Q&A

All C++ topics

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

  1. 1Containers — own and store elements.
  2. 2Iterators — generalize pointers to positions.
  3. 3Algorithms — generic operations over ranges.

Example

Example.cppcpp
#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

Example.cppcpp
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

Example.cppcpp
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

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits