Skip to main content

Lesson 3 of 7

Iterators - Categories, Invalidation & Custom Iterators

Iterators are the bridge between containers and algorithms. Every STL container exposes `begin()` / `end()` returning iterators, and every STL algorithm takes iterator ranges. **Iterator invalidation** is one of the most dangerous aspects of STL: modifying a container can invalidate existing iterators, leading to undefined behaviour. Knowing which operations invalidate which container's iterators prevents crashes.

12 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Iterator Categories, Invalidation Rules & Sentinel Pattern

Iterator Categories, Invalidation Rules & Sentinel Pattern
#include <iostream>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <algorithm>

void iterator_basics() {
    std::vector<int> v{1, 2, 3, 4, 5};

    // ── Forward iteration ──────────────────────────────────────
    for (auto it = v.begin(); it != v.end(); ++it) {
        std::cout << *it << " ";
    }
    std::cout << "
";

    // ── Reverse iteration ──────────────────────────────────────
    for (auto it = v.rbegin(); it != v.rend(); ++it) {
        std::cout << *it << " ";   // 5 4 3 2 1
    }
    std::cout << "
";

    // ── const_iterator - read-only ────────────────────────────
    for (auto it = v.cbegin(); it != v.cend(); ++it) {
        // *it = 99;  ← compile error: const_iterator
        std::cout << *it << " ";
    }
    std::cout << "
";

    // ── Pointer arithmetic (random-access iterators) ──────────
    auto mid = v.begin() + 2;     // random-access: O(1) (vector, deque)
    std::cout << *mid << "
";    // 3
    std::cout << (v.end() - v.begin()) << "
"; // 5 (number of elements)

    // std::list iterator: bidirectional but NOT random-access
    // std::list<int>::iterator lit = l.begin();
    // lit + 2;   ← compile error! No + for bidirectional iterators
    // std::advance(lit, 2);  ← O(n) but works for all iterators
}

// ── ITERATOR INVALIDATION RULES (CRITICAL) ───────────────────
// ┌──────────────┬─────────────────────────────────────────────┐
// │ Container    │ Invalidates on                              │
// ├──────────────┼─────────────────────────────────────────────┤
// │ vector       │ push_back (if realloc), insert, erase       │
// │              │ (all iters >= point of change)              │
// │ deque        │ push_front/back, insert, erase              │
// │ list         │ erase ONLY (other iters stable always!)     │
// │ map/set      │ erase ONLY (other iters stable always!)     │
// │ unordered_map│ insert (if rehash), erase                  │
// └──────────────┴─────────────────────────────────────────────┘

void vector_invalidation_demo() {
    std::vector<int> v{1, 2, 3, 4, 5};

    // DANGEROUS: erase while iterating with index
    // Correct erase-while-iterating pattern:
    for (auto it = v.begin(); it != v.end(); ) {
        if (*it % 2 == 0) {
            it = v.erase(it);   // erase returns next valid iterator!
        } else {
            ++it;
        }
    }
    for (int n : v) std::cout << n << " ";  // 1 3 5
    std::cout << "
";

    // push_back invalidation
    std::vector<int> w{1, 2, 3};
    auto& ref = w[0];            // reference to first element
    w.push_back(4);              // reallocation! ref is now DANGLING
    // std::cout << ref;         ← undefined behaviour if realloc happened
}

void list_stability_demo() {
    std::list<int> l{1, 2, 3, 4, 5};
    auto it = l.begin();        // points to 1
    std::advance(it, 2);        // points to 3

    l.push_front(0);            // list: all iterators STILL valid
    l.push_back(6);             // still valid
    l.erase(l.begin());         // erase 0 - 'it' still points to 3!

    std::cout << *it << "
";   // 3 - valid (list doesn't move elements)
}

int main() {
    iterator_basics();
    vector_invalidation_demo();
    list_stability_demo();
    return 0;
}

Common Mistakes

  • Storing an iterator into a vector then calling `push_back` - if `push_back` triggers reallocation, all stored iterators, pointers, and references into the vector are invalidated. Use `reserve()` upfront or use indices instead of iterators if you might push.
  • Erasing from a vector in a loop without updating the iterator - `v.erase(it)` invalidates `it` and all iterators after it. The return value of `erase` is the next valid iterator. `it = v.erase(it)` is the correct pattern.
  • Assuming `std::list` has O(1) indexing - `std::list` has no `operator[]`. To access the nth element: `auto it = l.begin(); std::advance(it, n);` - this is O(n). If random access is needed, `list` is the wrong container.

Tip

Tip

Practice Iterators Categories Invalidation Custom Iterators in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Bridging STL Containers to STL Algorithms via Standardized Traversal Categories

Practice Task

Note

Practice Task - (1) Write a working example of Iterators Categories Invalidation Custom Iterators from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Iterators Categories Invalidation Custom Iterators is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.

Key Takeaways

  • Iterators are the bridge between containers and algorithms.
  • Storing an iterator into a vector then calling `push_back` - if `push_back` triggers reallocation, all stored iterators, pointers, and references into the vector are invalidated. Use `reserve()` upfront or use indices instead of iterators if you might push.
  • Erasing from a vector in a loop without updating the iterator - `v.erase(it)` invalidates `it` and all iterators after it. The return value of `erase` is the next valid iterator. `it = v.erase(it)` is the correct pattern.
  • Assuming `std::list` has O(1) indexing - `std::list` has no `operator[]`. To access the nth element: `auto it = l.begin(); std::advance(it, n);` - this is O(n). If random access is needed, `list` is the wrong container.

Topics in This Module

0/7 done