Key takeaways
- STL questions test which container to choose and why — vector vs list vs deque, map vs unordered_map — plus their complexity guarantees.
- Know iterator invalidation, the erase–remove idiom,
emplacevspush, custom comparators and hashes. - In coding rounds, using the STL fluently (
sort,lower_bound,priority_queue,unordered_map) saves 10+ minutes.
The Standard Template Library is where C++ interviews meet data structures. Interviewers use STL questions to check that you choose containers for the right reasons and know their costs. Here are the most-asked questions with crisp answers and code. The full C++ interview questions page covers the rest of the language.
Containers
What are the main STL container categories?
- Sequence containers:
vector,deque,list,forward_list,array - Associative (ordered, red-black tree):
set,map,multiset,multimap - Unordered (hash table):
unordered_set,unordered_mapand their multi- variants - Adaptors:
stack,queue,priority_queue(built on other containers)
vector vs list vs deque — when do you use each?
| Operation | vector | deque | list |
|---|---|---|---|
| Random access | O(1) | O(1) | O(n) |
| Push/pop at the back | Amortised O(1) | O(1) | O(1) |
| Push/pop at the front | O(n) | O(1) | O(1) |
| Insert in the middle | O(n) | O(n) | O(1) given an iterator |
| Memory layout | Contiguous (cache-friendly) | Chunked | Scattered nodes |
Default to vector. Contiguous memory makes it the fastest in practice, even for many inserts on small or medium sizes. Use deque for queue-like push/pop at both ends, and list only when you need stable iterators and splicing.
How does vector grow? What do reserve and shrink_to_fit do?
When size() == capacity(), push_back allocates a larger buffer (typically 1.5× or 2× the old capacity), moves or copies the elements across and frees the old buffer — so the amortised cost is O(1), but every iterator and reference is invalidated. reserve(n) pre-allocates capacity to avoid repeated reallocations. shrink_to_fit() requests that unused capacity be released (the request is non-binding).
map vs unordered_map — what are the differences?
| map | unordered_map | |
|---|---|---|
| Structure | Red-black tree | Hash table |
| Order | Sorted by key | No order |
| Lookup / insert | O(log n) guaranteed | O(1) average, O(n) worst case |
| Key needs | operator< / a comparator | std::hash + operator== |
| Range queries | Yes (lower_bound, upper_bound) | No |
Use unordered_map for fast lookups; use map when you need ordering, range queries or a guaranteed worst case (also safer against hash-flooding attacks on untrusted input).
What is the difference between map's [] operator, at() and find()?
m[key] inserts a default-constructed value if the key is missing (and can't be used on a const map). at(key) throws std::out_of_range if the key is missing. find(key) returns an iterator (or end()) without inserting anything — use it, or contains() in C++20, for read-only checks.
std::map<std::string, int> m;
if (m["x"] == 0) {} // silently inserts "x" -> 0
if (auto it = m.find("y"); it != m.end()) std::cout << it->second;
if (m.contains("z")) {} // C++20How do you use priority_queue as a min-heap and with custom objects?
priority_queue is a max-heap by default. Pass std::greater<> for a min-heap, or a custom comparator for objects.
#include <queue>
#include <vector>
std::priority_queue<int, std::vector<int>, std::greater<int>> minHeap;
struct Task { int priority; std::string name; };
auto cmp = [](const Task& a, const Task& b) { return a.priority > b.priority; }; // smaller = higher priority
std::priority_queue<Task, std::vector<Task>, decltype(cmp)> pq(cmp);
pq.push({2, "build"}); pq.push({1, "test"});
// pq.top().name == "test"How do you use a custom struct as a key in unordered_map?
Provide a hash function and equality, either through template arguments or by specialising std::hash.
struct Point { int x, y; bool operator==(const Point&) const = default; };
struct PointHash {
size_t operator()(const Point& p) const noexcept {
return std::hash<long long>{}((static_cast<long long>(p.x) << 32) ^ static_cast<unsigned>(p.y));
}
};
std::unordered_map<Point, int, PointHash> grid;
grid[{1, 2}] = 5;Iterators and algorithms
What are the iterator categories?
Input → Forward → Bidirectional → Random-access → Contiguous (C++17/20), plus Output iterators. vector provides random-access (contiguous) iterators, list and map bidirectional, and forward_list forward. Algorithms state the category they need — std::sort requires random-access iterators, so use list.sort() for lists.
What is the erase–remove idiom?
std::remove / remove_if don't erase anything: they shift the kept elements forward and return the new logical end. You then call erase to actually shrink the container. In C++20, std::erase / std::erase_if do both steps in one call.
std::vector<int> v{1, 2, 3, 4, 5, 6};
v.erase(std::remove_if(v.begin(), v.end(), [](int x){ return x % 2 == 0; }), v.end());
// C++20:
std::erase_if(v, [](int x){ return x % 2 == 0; });emplace_back vs push_back?
push_back takes an existing object (copying or moving it in). emplace_back constructs the element in place from constructor arguments, avoiding a temporary. For an already-constructed object there's no difference; emplace_back helps when building from arguments. Beware: emplace_back can call explicit constructors that push_back would reject.
Which STL algorithms do you use most in coding rounds?
sort (with a custom comparator), stable_sort, lower_bound / upper_bound (binary search on sorted ranges), binary_search, accumulate / reduce, max_element / min_element, count_if, unique (after sorting), reverse, next_permutation, nth_element (average O(n) selection) and partial_sort.
std::vector<int> a{5, 1, 4, 1, 3};
std::sort(a.begin(), a.end()); // 1 1 3 4 5
auto it = std::lower_bound(a.begin(), a.end(), 4); // first element >= 4
int idx = static_cast<int>(it - a.begin()); // 3
a.erase(std::unique(a.begin(), a.end()), a.end()); // 1 3 4 5
std::nth_element(a.begin(), a.begin() + 1, a.end()); // a[1] is the 2nd smallestWhat are the complexity guarantees of std::sort and std::stable_sort?
std::sort is O(n log n) — usually introsort (quicksort switching to heapsort, plus insertion sort for small ranges) — and is not stable. std::stable_sort keeps equal elements in their original order and is O(n log n) when extra memory is available, O(n log² n) otherwise.
Common pitfalls interviewers probe
- Erasing elements while iterating with a range-based
forloop (use the iterator returned byerase, orerase_if) - Holding a reference or iterator into a
vectoracross apush_back - Using
m[key]for lookups and accidentally inserting keys - Sorting a
listwithstd::sort(it won't compile — uselist::sort) - Comparators that aren't strict weak orderings (for example using
<=), which causes undefined behaviour insort
Then practise on real problems with the DSA interview questions and revise the C++ interview questions. Test yourself with the C++ quiz.