Skip to content

Module 8 · The Standard Template Library — topic 7 of 7

Iterators

Iterators are the glue of the STL. Learn iterator categories, begin/end and reverse iterators, advance/next/distance, inserters, and iterator invalidation.

Beginner 13 min read·Lesson 37 of 40 in C++ Programming

Learning objectives

  • Use begin/end, cbegin/cend and rbegin/rend
  • Move iterators with next, prev, advance and distance
  • Recognise iterator categories and invalidation rules

Definition

An iterator is an object that points to an element in a range and can be advanced, compared and dereferenced; iterator categories (input, output, forward, bidirectional, random-access, contiguous) describe which operations it supports.

Introduction

An iterator generalises a pointer. For a vector it may literally be a pointer; for a list it is an object that follows next links; for a map it walks a tree. Algorithms only ask iterators to do a few operations, so they work with every container.

Why it matters

Every STL algorithm call uses iterators.

Understanding invalidation prevents crashes when modifying containers.

Detailed explanation

Categories: input/output (single pass, e.g. stream iterators), forward (multi-pass, ++), bidirectional (++ and --; list, set, map), random-access (+n, [], <; vector, deque, array), contiguous (vector, array, string).

std::next(it, n) / std::prev(it) return moved copies; std::advance(it, n) moves in place; std::distance(a, b) counts steps. These work for all categories (O(n) for non-random-access).

rbegin()/rend() iterate backwards; cbegin()/cend() give const iterators.

std::back_inserter(v) makes an output iterator that calls push_back, so algorithms can append to containers.

Invalidation: vector reallocation invalidates all; erase invalidates at/after the point. list/set/map erase invalidates only the erased element.

Syntax

C++
for (auto it = v.begin(); it != v.end(); ++it) std::cout << *it;
for (auto it = v.rbegin(); it != v.rend(); ++it) { /* backwards */ }
std::copy_if(v.begin(), v.end(), std::back_inserter(out), pred);
auto third = std::next(l.begin(), 2);
auto n = std::distance(v.begin(), it);
  • Compare with !=, not <, for generic code.
  • Dereference with *, access members with ->.
  • Include <iterator> for next/prev/inserters.

Code examples

Forward and reverse iteration

C++
#include <iostream>
#include <vector>
int main() {
std::vector<int> v{1, 2, 3, 4};
for (auto it = v.begin(); it != v.end(); ++it) *it *= 2;
for (auto it = v.rbegin(); it != v.rend(); ++it) std::cout << *it << ' ';
std::cout << '\n';
return 0;
}
Output
8 6 4 2

next, prev and distance

C++
#include <iostream>
#include <iterator>
#include <list>
int main() {
std::list<char> l{'a', 'b', 'c', 'd', 'e'};
auto it = std::next(l.begin(), 3);
std::cout << *it << ' ' << *std::prev(it) << ' ' << std::distance(l.begin(), it) << '\n';
return 0;
}
Output
d c 3

More examples

Algorithms writing through inserters and stream iterators

C++
#include <algorithm>
#include <iostream>
#include <iterator>
#include <map>
#include <vector>
int main() {
std::vector<int> marks{45, 82, 37, 91, 68, 23};
std::vector<int> passed;
std::copy_if(marks.begin(), marks.end(), std::back_inserter(passed), [](int m) { return m >= 40; });
std::copy(passed.begin(), passed.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << '\n';
std::map<std::string, int> m{{"a", 1}, {"b", 2}, {"c", 3}};
for (auto it = m.begin(); it != m.end();) {
if (it->second % 2 == 1) it = m.erase(it); // erase returns the next valid iterator
else ++it;
}
std::cout << m.size() << ' ' << m.begin()->first << '\n';
return 0;
}
Output
45 82 91 68 
1 b

Step-by-step explanation

  • back_inserter lets copy_if grow passed with push_back.
  • ostream_iterator writes each element to cout followed by a space.
  • m.erase(it) returns the iterator after the erased element, so the loop stays valid.
  • Only "b" (value 2) remains.

Expected output

Running “Algorithms writing through inserters and stream iterators” prints exactly:

TextOutput
45 82 91 68
1 b

Practical applications

  • Generic libraries are written against iterator concepts.
  • Stream iterators read and write data files with algorithms.
  • Erase-while-iterating is common in caches and game loops.

Best practices

  • Prefer range-for or algorithms to manual iterator loops.
  • Use auto for iterator types.
  • Follow each container's invalidation rules.

Common mistakes

Using an erased iterator

Avoid

for (auto it = m.begin(); it != m.end(); ++it) if (bad(*it)) m.erase(it);

Prefer

for (auto it = m.begin(); it != m.end();) it = bad(*it) ? m.erase(it) : std::next(it);

After erase, it is invalid; use the iterator that erase returns.

Comparing iterators from different containers

Avoid

std::sort(a.begin(), b.end());

Prefer

std::sort(a.begin(), a.end());

Both iterators must belong to the same range.

Important notes

  • C++20 ranges and views (filter, transform) compose lazily without explicit iterators.
  • Raw pointers are valid random-access iterators for built-in arrays.

Key takeaways

  • Iterators generalise pointers; categories define allowed operations.
  • next/prev/advance/distance work for all categories.
  • erase returns the next valid iterator for node-based containers.

Try it yourself

  1. 1
    Print a vector in reverse using reverse iterators and ostream_iterator.
  2. 2
    Use std::transform with back_inserter to square every element into a new vector.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

6 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • ModerateWhat is printed?
  • ModerateWhat is wrong with erasing in this loop? `for (auto it = m.begin(); it != m.end(); ++it) if (it->second == 0) m.erase(it);`
Practise this topic