
Recall first from Associative containers, hash tables, and adaptors
- std::set and std::map keep keys sorted in a balanced tree with O(log n) lookup; the multi versions allow equivalent keys
- Unordered containers hash keys into buckets; average lookup is O(1), worst case O(n), and rehashing happens when size exceeds bucket_count times max_load_factor (default 1.0)
- Adaptors restrict an underlying container: stack and queue default to deque, priority_queue defaults to vector and is a max-heap unless you pass std::greater<>
The category ladder: what an iterator promises
3 min readThe previous lesson chose containers by their lookup behavior. This lesson asks what iterators promise about traversal, from input to contiguous, and which push_back, insert, and erase operations invalidate them.
An an object that refers to an element of a container (or a stream) and supports a defined set of traversal operations, such as *it and ++it is the glue between containers and algorithms. The STL was designed around one idea: an algorithm like sort should work on any sequence, without knowing what holds the elements. In C you approximate this with raw pointers plus metadata: qsort and bsearch (see their man pages) take a base pointer, an element count, an element size and a comparator. Iterators replace that loose bundle with a typed object whose capabilities the compiler can check.
Those capabilities are grouped into six categories, each adding guarantees:
- Input: read the pointed-to value with
*it, move forward with++it. Single pass only: once you increment, earlier positions may be gone.std::istream_iteratoris the classic example, reading values from a stream. - Output: write with
*it = value, move forward. Also single pass.std::ostream_iteratorandstd::back_insert_iteratorare output iterators. - Forward: read and write, and multi pass: you can save a copy of an iterator, increment the original, and the copy still refers to its element. You can traverse the same sequence repeatedly.
- Bidirectional: everything forward offers, plus
--itto step backward. - Random access: constant-time jumps:
it + n,it - n,it[n],it2 - it1, and ordering with<. Sorting needs this. - Contiguous (formalized in C++20): random access plus the guarantee that elements sit next to each other in memory, like a C array, so
std::to_address(it)gives a usable pointer.
Each stronger category keeps the weaker guarantees (output is the separate write-only branch). Since C++20 you can test the contract at compile time with concepts from <iterator>:
#include <iterator>
#include <vector>
#include <list>
#include <deque>
static_assert(std::contiguous_iterator<std::vector<int>::iterator>);
static_assert(std::bidirectional_iterator<std::list<int>::iterator>);
static_assert(std::random_access_iterator<std::deque<int>::iterator>);
static_assert(!std::contiguous_iterator<std::deque<int>::iterator>);
The last line is the famous trap: a deque iterator supports it + n, but the elements live in several separate blocks, so it is random access and not contiguous. The mapping for the containers you know:
| Container | Iterator category |
|---|---|
vector, string, array |
contiguous |
deque |
random access |
list, map, set (and multi versions) |
bidirectional |
forward_list, all unordered_* |
forward |
stack, queue, priority_queue |
none: adaptors expose no iterators |
Invalidation: which operations break which iterators
3 min reada container operation making previously obtained iterators (and sometimes references or pointers) unusable; dereferencing or incrementing an invalidated iterator is undefined behaviour is the single largest source of STL crashes, and the rules are precise, not vague. Learn them per container.
vector and string (contiguous storage). push_back has two cases. If size is below capacity, no reallocation happens: only the end() iterator is invalidated, and iterators to existing elements stay valid. If the buffer is full, the container allocates a larger buffer, moves the elements and frees the old one: every iterator, pointer and reference dies. insert follows the same reallocation rule, and even without reallocation it invalidates iterators at and after the insertion point (elements shifted right). erase invalidates iterators and references at and after the erased position, including end(); earlier ones survive. reserve invalidates everything if it grows capacity, nothing otherwise.
deque (block map plus fixed-size blocks). Inserting at either end (push_back, push_front) invalidates all iterators, but references to existing elements stay valid: the elements themselves never move, only the block directory may be rebuilt. Inserting in the middle invalidates all iterators and references. Erasing at either end invalidates only iterators and references to the erased elements (plus end() when erasing at the back); erasing in the middle invalidates everything. This asymmetry is unique to deque and worth memorizing.
list and forward_list (one node per element). insert, emplace and splice never invalidate anything. erase invalidates only iterators and references to the erased elements. Every other node keeps its address, so saved iterators survive arbitrary edits elsewhere.
map, set, multimap, multiset (red-black tree nodes). Same guarantee as list: insertion never invalidates iterators or references, and erase invalidates only the erased element's iterators. This is why holding an iterator into a std::map across insertions is a common, safe pattern.
unordered_map, unordered_set and friends (bucket array plus element nodes). erase invalidates only the erased element. Insertion is the interesting case: if the new element pushes the load factor past its limit, the container rehashes, rebuilding the bucket array. A rebuilding the bucket array of a hash table so elements are redistributed among a new set of buckets invalidates all iterators, because iterators walk buckets. But the element nodes themselves are only relinked, never moved, so references and pointers to elements remain valid. rehash and reserve follow the same rule. Note that operator[] can insert, so even a lookup-style call can trigger a rehash.
array has fixed size: no operation inserts or erases, so nothing invalidates. The adaptors from the previous lesson expose no iterators at all, so the question does not arise.
Two rules separate them: deque end-inserts kill iterators but keep references, and unordered rehash kills iterators but keeps references and pointers. For vector reallocation, both die together. When you decide what to cache across a mutation (an iterator, a reference, or an index), check which of the three the operation actually invalidates.
Loops that survive mutation
2 min readThe classic bug is erasing inside a loop and then incrementing the dead iterator:
// WRONG: it is invalidated by erase, then ++it is undefined behaviour
for (auto it = v.begin(); it != v.end(); ++it)
if (*it % 2 == 0)
v.erase(it);
The fix uses the return value: erase returns an iterator to the element that followed the erased one (or end()), and insert returns an iterator to the newly inserted element. Both are valid by definition, so the loop becomes:
std::vector<int> v{1, 2, 3, 4, 5, 6};
for (auto it = v.begin(); it != v.end(); ) {
if (*it % 2 == 0)
it = v.erase(it); // fresh iterator to the next element
else
++it;
}
// v now holds 1, 3, 5
Notice there is no ++it in the loop header: each branch advances exactly once. This pattern works for every container, because the return-value guarantee is universal even where the invalidation rules differ.
The second pattern removes the hazard instead of repairing it: reserve enough capacity up front so no push_back can reallocate while you hold an iterator.
std::vector<int> v;
v.reserve(1000);
v.push_back(0);
auto first = v.begin(); // no reallocation can happen below
for (int i = 1; i < 1000; ++i)
v.push_back(i); // within capacity: first stays valid
The third pattern applies to hash tables: if you must insert while iterating an unordered_map, either re-obtain iterators after the insertion, or collect the keys first and insert in a second pass. And when you need iterators that survive edits as a design requirement, that is a reason to choose list or map over vector: the node-based guarantee is part of the container's contract, not luck.
Know the storage: contiguous (vector), blocks (deque), or nodes (list, map, unordered).
Check the operation's rule: does it reallocate, rehash, shift, or relink?
Use the return value: assign the result of erase or insert back to your iterator.
Prevent the hazard when you can: reserve capacity, or pick a node-based container.
One caution about cost: erasing from the middle of a vector shifts every later element, so an erase loop over a large vector is quadratic. The next lesson, "Algorithms and the erase-remove idiom", shows how std::remove_if plus a single erase does the same job in one linear pass, and how the algorithm library builds on exactly the category guarantees you learned here.
Key takeaways
- vector iterators are contiguous; deque iterators are random access but not contiguous
- vector push_back invalidates everything on reallocation, otherwise only end()
- list, map and set invalidate only iterators to erased elements; insert never invalidates
- An unordered container rehash invalidates all iterators but keeps references and pointers to elements valid
Reflect
- Explain to a colleague, in two sentences: name the six iterator categories and the operations each one guarantees
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
Official documentation first. Links checked when the lesson was published.