Skip to content
AgileLogics
4 min read

Iterators

Prerequisites: Maps & associative containers

An iterator is a generalized pointer — it can be dereferenced with * and advanced with ++, uniformly, regardless of the container's actual internal layout:

std::vector<int> nums = {10, 20, 30};

for (auto it = nums.begin(); it != nums.end(); ++it) {
    std::cout << *it << std::endl;
}

A modern range-based for loop (for (int n : nums), used throughout this course so far) is really just shorthand the compiler expands into this exact iterator pattern — understanding what's underneath it makes clear why any container supporting .begin()/.end() works with a range-based for loop automatically.

Common mistakes

  • Using it != nums.end() after modifying the container (adding or removing elements) — many operations invalidate existing iterators, making further use of them undefined behavior.