C++ ยท Chapter 46 of 49

C++ Iterators

An iterator is an object that points to an element inside a container and can be advanced to visit the next one, generalising the idea of a pointer for STL containers. `.begin()` returns an iterator to the first element and `.end()` returns one past the last.

Iterators are the glue that lets generic STL algorithms work with any container type, since algorithms operate on iterator ranges rather than specific container types.

Using iterators

`for (auto it = v.begin(); it != v.end(); ++it) { std::cout << *it; }` manually walks a vector, dereferencing `*it` to get the current value.

Types of iterators

Vectors support random-access iterators (can jump anywhere), while lists support bidirectional iterators (only step forward/back one at a time).

Example 1 (cpp)
std::vector<int> v = {1, 2, 3};
for (auto it = v.begin(); it != v.end(); ++it) {
    std::cout << *it;
}
Output
123

The iterator it walks from begin() to end(), dereferenced with *it.

Key points

  • begin() points to the first element; end() points past the last.
  • *it dereferences an iterator to access its value.
  • ++it advances the iterator to the next element.
  • Iterators let generic algorithms work across container types.
๐Ÿ’ก Note: Modifying a vector's size while iterating over it can invalidate iterators โ€” be cautious inserting/erasing during a loop.

๐Ÿ“ Quick Quiz

1. What does *it do to an iterator?

2. What does end() point to?

3. Iterators generalise the concept of a: