Skip to content

Iterator

Difficulty: Intermediate

Key concepts

  • iterator pattern
  • iterator categories
  • ranges
  • iterator invalidation
  • begin and end
  • What the Iterator pattern is for: walking through a collection’s elements in a meaningful order, without knowing how the collection stores them.
  • How C++ turns the pattern into conventions that the whole standard library relies on: begin and end, *, ++, and ==, iterator categories, and C++20 ranges.
  • How to write a small, correct iterator for your own container, so that range-for, standard algorithms, and generic code all work on it.
  • When an iterator stops being valid, how to document it, and why breaking the rule is dangerous even when nothing crashes.

A greenhouse controller records a temperature every minute. It must keep only the most recent readings, a fixed number of them, without allocating memory while it runs. The standard answer is a ring buffer: a fixed array where, once it is full, each new reading replaces the oldest.

  1. FR-1 Keep the last N readings; a new reading replaces the oldest once N are held.
  2. FR-2 Code that uses the readings (the display, the alarms, the statistics) sees them oldest to newest.
  3. FR-3 That code can use ordinary C++: range-for, standard algorithms such as std::ranges::max_element, and generic functions that also accept a std::vector.
  4. C-1 (constraint) No allocation after construction, and no copy of the readings just to read them.

The difficulty is that storage order is not reading order. With room for 4 and six readings pushed, the array holds the fifth and sixth readings where the first and second used to be.

Expose the storage and where the oldest reading is, and let callers work out the order:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

before.hpp
namespace before {
// Keeps the last `capacity` readings. To read them in order, start at
// oldest() and wrap around the end of storage().
//
// This is the version without the Iterator pattern. Until it is full,
// push() appends; after that, each push overwrites the oldest slot and
// moves oldest() one slot on, wrapping from the last slot back to 0. So
// once the buffer has wrapped, storage order is no longer reading order,
// and every caller has to know that and do the wrap-around arithmetic.
class Readings {
public:
// Throws std::invalid_argument if capacity is 0: a buffer that holds
// nothing is never what the caller meant. `explicit` stops a bare
// number from being turned into a Readings by accident.
explicit Readings(std::size_t capacity); // throws if 0
void push(double value);
// The leak in this design: callers get the raw vector, in storage
// order, by const reference (they can read it but not change it).
const std::vector<double>& storage() const { return storage_; }
// The index in storage() of the oldest reading. Always 0 until the
// buffer first fills; callers need it to read in order.
std::size_t oldest() const { return oldest_; }
std::size_t size() const { return storage_.size(); }
std::size_t capacity() const { return capacity_; }
private:
std::vector<double> storage_; // grows to capacity_, then reused in place
std::size_t capacity_;
std::size_t oldest_ = 0; // slot the next push overwrites, once full
};
} // namespace before

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// Six readings into room for four: the last two pushes overwrite the
// first two, so the buffer has wrapped round once.
before::Readings old_readings{4};
for (double t : temperatures) {
old_readings.push(t);
}
std::cout << "before, in storage order:";
// Storage order: slots 0, 1, 2, 3 hold 20.5 19.5 21.5 22, because
// 20.5 and 19.5 overwrote the two oldest readings in slots 0 and 1.
for (double t : old_readings.storage()) { // wrong once the buffer has wrapped
std::cout << ' ' << t;
}
std::cout << "\nbefore, with the index arithmetic:";
// Reading order: the i-th oldest reading is i slots after oldest()
// (here 2), wrapping past the last slot with % capacity(). Slots 2, 3,
// 0, 1 give 21.5 22 20.5 19.5. Every caller would have to write this.
for (std::size_t i = 0; i < old_readings.size(); ++i) {
std::cout << ' ' << old_readings.storage()[(old_readings.oldest() + i) % old_readings.capacity()];
}
std::cout << '\n';

The first two lines of the output, under Check, show the problem: walking storage() in order gives 20.5 19.5 21.5 22, which is not the order the readings were taken. The second loop is right, but only because its author knew the layout.

  • Every caller repeats the arithmetic (oldest + i) % capacity, and each copy is a chance for a mistake. The first loop looks correct, compiles, and is correct until the buffer first wraps around, which may not happen in a short test.
  • The layout is now part of the interface. Changing it, for example to store the newest first, breaks every caller.
  • FR-3 fails. Range-for and the standard algorithms see the std::vector in storage order; nothing gives them reading order.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_ring_buffer.cpp
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure
// if the condition is false. LLD_CHECK_EQ(actual, expected) does the same
// for actual == expected and also prints both values when they differ.
// They come from the site's small test header, lld_test.hpp.
//
// Room for 3, four pushes: 4 overwrites 1 in slot 0, and oldest() moves
// to slot 1. The test pins down the layout a caller is forced to know.
LLD_TEST(before_storage_order_is_not_the_reading_order_after_a_wrap) {
before::Readings readings{3};
for (double t : {1.0, 2.0, 3.0, 4.0}) {
readings.push(t);
}
// The caller must know that 2 is the oldest and that 4 sits before it.
// The extra brackets round the vector are needed because the macro
// would otherwise split its argument at the commas inside the braces.
LLD_CHECK(readings.storage() == (std::vector<double>{4.0, 2.0, 3.0}));
LLD_CHECK_EQ(readings.oldest(), std::size_t{1});
}

A first improvement is an index function, at(i), that does the arithmetic once inside the class. That hides the layout and is enough for many classes. It still does not give FR-3: the algorithms, the range-for loop, and generic code all speak iterators.

Iterator moves the job of walking a collection into a separate small object, the iterator, which knows the current position and how to get to the next one. The collection hands out iterators; callers use only the iterator’s operations and never see the storage.

Its participants:

  • The iterator: an object for one position in one collection, with operations to read the element there and move to the next. Here, RingBuffer<T>::const_iterator.
  • The collection (the “aggregate”): hands out iterators to its first element and to one past its last. Here, RingBuffer<T>, with begin() and end().
  • The client: walks from begin() to end(). Here, the loops in main, the generic average, and the standard algorithms.

Classic descriptions give the iterator named functions, such as first(), next(), is_done(), and current(), behind an interface with virtual functions. C++ uses the same idea with a different spelling, and without virtual functions:

Classic iterator C++ iterator Meaning
first() c.begin() a position at the first element
is_done() it == c.end() past the last element
current() *it (and it->m) the element at this position
next() ++it move to the next position

Any type with these operations is an iterator, checked at compile time by templates and, since C++20, by concepts such as std::forward_iterator. That is why one std::ranges::max_element works on a std::vector, a std::list, an array, and the ring buffer below, with no common base class and no virtual call per step.

Not every collection can offer every operation cheaply. The standard library sorts iterators into categories; each adds operations to the one before:

Category Adds Example
input read each element once, going forward reading from a stream
forward can walk again; copies stay valid std::forward_list
bidirectional --it std::list, std::map
random access it + n, it[n], it2 - it1, < std::deque
contiguous (C++20) elements are next to each other in memory std::vector, arrays

Algorithms ask for the category they need: std::ranges::max_element needs forward, std::ranges::sort needs random access. An iterator should offer the category its collection can support cheaply, and no more than its clients need.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

ring_buffer.hpp
// Keeps the last `capacity` values pushed; when full, a push replaces
// the oldest. Iteration goes from the oldest value to the newest.
//
// It is a class template: `T` is the type of value stored, chosen by the
// user, so RingBuffer<double> holds doubles and RingBuffer<std::string>
// holds strings. The layout (which slot holds which value) stays private;
// callers see only begin() and end(), and the iterator they return walks
// the values in the order they were pushed.
template <typename T>
class RingBuffer {
public:
// Declares the nested iterator class now, so begin() and end() below
// can name it. Its full definition comes after RingBuffer.
class const_iterator;
// Reserves room for `capacity` values up front, so later pushes never
// allocate. Throws std::invalid_argument if capacity is 0: there would
// be no slot to put a value in, and `% capacity_` would divide by 0.
explicit RingBuffer(std::size_t capacity) : capacity_{capacity} {
if (capacity == 0) {
throw std::invalid_argument("a ring buffer needs a capacity of at least 1");
}
storage_.reserve(capacity);
}
// Invalidates every iterator into this buffer.
//
// Two cases. While the buffer is not yet full, the value is appended,
// and oldest_ stays 0. Once it is full, the value overwrites the oldest
// one, in slot oldest_, and oldest_ moves one slot on; `% capacity_`
// makes it wrap from the last slot back to 0. `value` is taken by value
// and then moved into the slot (std::move), so a std::string, say, is
// not copied a second time.
void push(T value) {
if (storage_.size() < capacity_) {
storage_.push_back(std::move(value));
return; // still filling up: nothing is overwritten
}
storage_[oldest_] = std::move(value); // the new value replaces the oldest
oldest_ = (oldest_ + 1) % capacity_; // the next slot now holds the oldest
}
std::size_t size() const { return storage_.size(); }
std::size_t capacity() const { return capacity_; }
bool empty() const { return storage_.empty(); }
// begin() is position 0 (the oldest value); end() is position size(),
// one past the newest, which is never read. `this` is a pointer to
// this buffer, so the iterator knows which buffer to read from. Both
// are const: they only hand out read-only iterators.
const_iterator begin() const { return const_iterator{this, 0}; }
const_iterator end() const { return const_iterator{this, size()}; }
private:
// The value `position` places after the oldest one.
// This is the only place that knows the layout. The oldest value sits
// in slot oldest_, the next in oldest_ + 1, and so on, wrapping past
// the last slot back to 0, which is what `% capacity_` does. Before the
// buffer is full, oldest_ is 0 and position is simply the slot.
const T& at_position(std::size_t position) const { return storage_[(oldest_ + position) % capacity_]; }
std::vector<T> storage_; // grows to capacity_, then is reused in place
std::size_t capacity_;
std::size_t oldest_ = 0; // where the oldest value is, once full
};
How this code works: push and at_position, traced

main.cpp pushes six temperatures, 18.5, 19, 21.5, 22, 20.5, and 19.5, into a RingBuffer<double> with capacity 4.

  1. The first four pushes find storage_.size() < capacity_, so they append and return early. oldest_ stays 0.
  2. From the fifth push on, the buffer is full. Each push overwrites slot oldest_ and then moves oldest_ on by one, wrapping with % capacity_.
Push Value Branch storage_ after oldest_ after
1 18.5 append 18.5 0
2 19 append 18.5, 19 0
3 21.5 append 18.5, 19, 21.5 0
4 22 append 18.5, 19, 21.5, 22 0
5 20.5 overwrite 20.5, 19, 21.5, 22 1
6 19.5 overwrite 20.5, 19.5, 21.5, 22 2
  1. Reading in order. at_position(p) reads slot (oldest_ + p) % capacity_, which is (2 + p) % 4 here:
Position p Slot (2 + p) % 4 Value
0 (oldest) 2 21.5
1 3 22
2 0 20.5
3 (newest) 1 19.5

That is the oldest to newest: 21.5 22 20.5 19.5 line of the output. The arithmetic is the same as the before-version’s caller loop, but it is now written once, inside the class.

  • The storage is private. Nothing outside the class sees storage_ or oldest_, so the layout can change without breaking callers.
  • at_position does the arithmetic once. Position 0 is the oldest reading, position size() - 1 the newest. It is private: only the iterator calls it.
  • begin() and end() are const and return a const_iterator. Readings are not edited once recorded, so there is no mutable iterator (see Design choices).
  • No allocation after construction (C-1). The vector reserves its capacity once; push either appends within that capacity or overwrites in place.
  • push documents what it does to iterators, in the same way the standard containers do.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

ring_buffer.hpp
// The iterator: a small object that remembers which buffer it reads and
// how far along it is, counted from the oldest value. `*it` reads the
// value there, `++it` moves one value on, and `it == other` asks whether
// two iterators are at the same place. That is all range-for and the
// standard algorithms need. It never changes the buffer (hence const_).
// `RingBuffer<T>::const_iterator` names the class declared inside
// RingBuffer above; `template <typename T>` is repeated because it
// belongs to the template.
template <typename T>
class RingBuffer<T>::const_iterator {
public:
// Five type names the standard library looks up to learn what this
// iterator is: its category (forward: it only moves forwards, and a
// copy can walk over the same values again), the type of value it
// visits, the signed type for the distance between two iterators,
// and what operator-> and operator* return.
using iterator_category = std::forward_iterator_tag;
using value_type = T;
using difference_type = std::ptrdiff_t;
using pointer = const T*;
using reference = const T&;
// Forward iterators must be default-constructible. Such an iterator
// points at no buffer (buffer_ is nullptr) and must not be read.
const_iterator() = default;
// Read the value at this position: the buffer does the wrap-around.
// It returns a const reference, so nothing is copied.
reference operator*() const { return buffer_->at_position(position_); }
// it->member: `**this` calls operator* above to get the value, and
// `&` takes its address. Lets callers write it->size() for strings.
pointer operator->() const { return &**this; }
// Pre-increment, ++it: move on one value and return this iterator.
// A plain + 1, because positions count from the oldest, not slots.
const_iterator& operator++() {
++position_;
return *this;
}
// Post-increment, it++: the unused `int` parameter is how C++ tells
// this form apart from ++it. It keeps a copy of where the iterator
// was, moves on with ++*this (the function above), and returns the
// copy, so `auto before = it++;` gets the old position.
const_iterator operator++(int) {
const_iterator before = *this;
++*this;
return before;
}
// `= default` compares the members one by one: equal only if both
// iterators read the same buffer and are at the same position. This
// is how a loop knows it has reached end().
bool operator==(const const_iterator&) const = default;
private:
// Only RingBuffer may call the private constructor below, so only
// begin() and end() can make an iterator that points into a buffer.
friend class RingBuffer;
const_iterator(const RingBuffer* buffer, std::size_t position) : buffer_{buffer}, position_{position} {}
const RingBuffer* buffer_ = nullptr; // observes; the buffer must outlive the iterator
std::size_t position_ = 0; // 0 is the oldest value; size() is the end
};
How this code works: What range-for does with the iterator

The loop for (double t : readings) { ... } in main.cpp is shorthand. The compiler turns it into roughly this:

  1. auto it = readings.begin(); makes an iterator with position 0.
  2. auto last = readings.end(); makes one with position size(), 4.
  3. While it != last: C++20 writes != for you from the defaulted operator==. Both iterators hold the same buffer pointer, so only the positions decide.
  4. double t = *it; calls operator*, which calls at_position with the iterator’s position and gets the value back.
  5. The loop body runs with t.
  6. ++it; calls the pre-increment, which adds 1 to the position. Back to step 3.

With the four values from the trace above, it takes positions 0, 1, 2, and 3, reading 21.5, 22, 20.5, and 19.5. When its position reaches 4 it equals last and the loop stops; position 4 is never read. The standard algorithms (max_element, find_if, …) do the same three things, *, ++, and ==, so they work too.

  • It stores a position, not an array index. position_ counts from the oldest reading, so ++ is a plain increment, and end() is simply position size(). The wrap-around is handled in one place, at_position. An iterator that stored an array index would need to wrap in ++, and could not tell begin() from end() when the buffer is full, since both would point at the same slot.
  • The five type names tell the standard library what kind of iterator this is. iterator_category (or C++20’s iterator_concept) names the category, and C++20 concepts check it along with value_type and difference_type; pointer and reference are for older code.
  • It is default-constructible, copyable, and comparable with ==. std::forward_iterator requires all three. The defaulted operator== compares the buffer pointer and the position, so two iterators are equal only if they point at the same place in the same buffer.
  • operator++() and operator++(int). The first (pre-increment) moves and returns the iterator; the second (post-increment) returns a copy of where it was. Both are expected.
  • operator-> lets callers write it->size() for buffers of strings or structs.
  • Only RingBuffer can make an iterator that points into a buffer. The two-argument constructor is private, and RingBuffer is a friend. A nested class can already read the buffer’s private members; the friend is needed the other way round.
  • It observes the buffer through a plain const RingBuffer*. It owns nothing, so copying an iterator is cheap, and the buffer must outlive it.
RingBuffer hands out const_iterators; each iterator observes the buffer and holds only a position
Text description of the diagram

A class diagram with three boxes. RingBuffer of T holds a vector of T called storage_, a capacity, and the index of the oldest value. Its public functions are push, size, capacity, empty, begin, and end, and it has a private at_position, which returns the value at a position counted from the oldest. const_iterator holds a pointer to a constant RingBuffer and a position; its functions are the operators star (read the value), arrow, plus-plus (pre- and post-increment), and equals, written out in words because the diagram cannot show operator symbols. A Client box stands for range-for loops, standard algorithms, and the average function. A dashed arrow from RingBuffer to const_iterator shows that begin and end create iterators. A solid arrow from const_iterator to RingBuffer shows that each iterator observes its buffer without owning it. Dashed arrows from the client show that it calls begin and end on the buffer and then uses only the iterators.

Diagram source (Mermaid)
classDiagram
class RingBuffer~T~ {
  -vector~T~ storage_
  -size_t capacity_
  -size_t oldest_
  +push(T value) void
  +size() size_t
  +capacity() size_t
  +empty() bool
  +begin() const_iterator
  +end() const_iterator
  -at_position(size_t) const T&
}
class const_iterator {
  -const RingBuffer* buffer_
  -size_t position_
  +operator_star() const T&
  +operator_arrow() const T*
  +operator_plus_plus() const_iterator&
  +operator_equals(other) bool
}
class Client {
  range-for, algorithms, average()
}
RingBuffer~T~ ..> const_iterator : begin() and end() create
const_iterator --> RingBuffer~T~ : buffer_ (observes)
Client ..> const_iterator : uses
Client ..> RingBuffer~T~ : calls begin() and end()

class RingBuffer<T>

the collection: keeps the last capacity values

Data members

  • std::vector<T> storage_; reserved once; reused in place when full
  • std::size_t capacity_;
  • std::size_t oldest_; where the oldest value is, once full
  • const T& at_position(std::size_t position) const; private: used by the iterator

Member functions

  • explicit RingBuffer(std::size_t capacity); throws if 0
  • void push(T value); invalidates every iterator
  • std::size_t size() const;
  • std::size_t capacity() const;
  • bool empty() const;
  • const_iterator begin() const; the oldest value
  • const_iterator end() const; one past the newest

class RingBuffer<T>::const_iterator

the iterator: a forward iterator

Data members

  • const RingBuffer* buffer_; observes: the buffer must outlive it
  • std::size_t position_; 0 is the oldest; size() is the end

Member functions

  • const T& operator*() const;
  • const T* operator->() const;
  • const_iterator& operator++();
  • const_iterator operator++(int);
  • bool operator==(const const_iterator&) const; defaulted
The ring buffer and its iterator

The outline leaves out the iterator’s type names and its private constructor.

Generic code: one function for every range

Section titled “Generic code: one function for every range”

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

stats.hpp
// Works on any forward range of numbers: a std::vector, a RingBuffer, ...
// Returns the mean of the values, or 0.0 for an empty range.
//
// `template <std::ranges::forward_range Range>` makes one function for
// every argument type, with a rule: the type must be a forward range
// (it has begin() and end(), and its iterators are forward iterators).
// Pass anything else and the compiler refuses, naming that rule.
template <std::ranges::forward_range Range>
double average(const Range& values) {
double sum = 0.0;
std::size_t count = 0; // counted here, so the range need not have size()
// Range-for calls values.begin() and values.end() and steps with ++,
// so for a RingBuffer the values arrive oldest first.
for (const auto& value : values) {
sum += value;
++count;
}
// An empty range would divide by 0, so it is given 0.0 instead.
// static_cast<double> turns the count into a double for the division.
return count == 0 ? 0.0 : sum / static_cast<double>(count);
}

average knows nothing about ring buffers. It asks only that its argument is a forward range: something with begin and end whose iterators are forward iterators. The C++20 concept std::ranges::forward_range checks that when the template is used, so a call with an argument that is not a forward range fails with an error that names the concept. (The element type is not constrained: a range of strings would fail inside the body instead.) This is the payoff of the pattern: the code that uses the readings is written once, for any collection.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// The same six readings into a RingBuffer of four doubles.
RingBuffer<double> readings{4};
for (double t : temperatures) {
readings.push(t);
}
std::cout << "oldest to newest:";
// Range-for asks readings for begin() and end() and walks between
// them; the iterator does the wrap-around, so no arithmetic here.
for (double t : readings) {
std::cout << ' ' << t;
}
std::cout << '\n';
// One generic average(), used on the buffer and on a plain vector.
std::cout << "average: " << average(readings) << " (all six: " << average(temperatures) << ")\n";
// Standard algorithms take the whole range. max_element and find_if
// return an iterator, so `*` reads the value it points at. count_if
// counts the values for which the lambda (a small unnamed function)
// returns true. Both are safe to read here: the buffer is not empty,
// and 21.5 is below 22, so find_if does find a value.
std::cout << "highest: " << *std::ranges::max_element(readings) << '\n';
std::cout << "above 20: " << std::ranges::count_if(readings, [](double t) { return t > 20.0; }) << '\n';
const auto first_cool = std::ranges::find_if(readings, [](double t) { return t < 22.0; });
std::cout << "first below 22: " << *first_cool << '\n';
Expected output
before, in storage order: 20.5 19.5 21.5 22
before, with the index arithmetic: 21.5 22 20.5 19.5
oldest to newest: 21.5 22 20.5 19.5
average: 20.875 (all six: 20.1667)
highest: 22
above 20: 3
first below 22: 21.5
oldest before a push: 21.5
oldest after a push: 22

Read the output against the requirements:

  • oldest to newest: 21.5 22 20.5 19.5 (FR-1, FR-2). The first two of the six readings were replaced, and the loop sees the rest in the order they were taken, with no arithmetic in the caller.
  • average: 20.875 (all six: 20.1667) (FR-3). The same average ran on the ring buffer and on the std::vector of all six readings: (21.5 + 22 + 20.5 + 19.5) / 4 = 20.875, and 121 / 6 is about 20.1667.
  • highest, above 20, and first below 22 came from std::ranges::max_element, count_if, and find_if, unchanged standard algorithms. find_if returned the first match in reading order, 21.5; in storage order it would have been 20.5.
  • No copy of the readings was made to read them (C-1).

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_ring_buffer.cpp
// static_assert is checked by the compiler: if the condition is false,
// the file does not compile. These two ask the C++20 concepts whether the
// iterator is a forward iterator and the buffer a forward range.
static_assert(std::forward_iterator<RingBuffer<int>::const_iterator>);
static_assert(std::ranges::forward_range<const RingBuffer<int>>);
// Before the wrap: two values, in push order. After five pushes into room
// for 3, the 1 and 2 are gone and 3, 4, 5 come out oldest first, even
// though 4 and 5 now sit in slots 0 and 1. to_vector is the small helper
// at the top of the test file: it copies the values out in visiting order.
LLD_TEST(iteration_goes_from_oldest_to_newest_before_and_after_a_wrap) {
RingBuffer<int> buffer{3};
buffer.push(1);
buffer.push(2);
LLD_CHECK(to_vector(buffer) == (std::vector<int>{1, 2}));
buffer.push(3);
buffer.push(4);
buffer.push(5);
LLD_CHECK(to_vector(buffer) == (std::vector<int>{3, 4, 5}));
LLD_CHECK_EQ(buffer.size(), std::size_t{3});
}
// With nothing pushed, begin() and end() are both position 0, so they
// are equal and a loop runs no times. std::ranges::distance counts the
// steps from begin() to end().
LLD_TEST(an_empty_buffer_has_nothing_to_visit) {
const RingBuffer<int> buffer{2};
LLD_CHECK(buffer.begin() == buffer.end());
LLD_CHECK_EQ(std::ranges::distance(buffer), std::ptrdiff_t{0});
}
// After the wrap the buffer holds 40, 20, 30 (10 was overwritten). The
// algorithms see exactly those: the highest is 40, the average is
// (40 + 20 + 30) / 3 = 30, and find returns end() ("not found") for 10.
LLD_TEST(standard_algorithms_and_generic_code_work_on_the_buffer) {
RingBuffer<double> buffer{3};
for (double t : {10.0, 40.0, 20.0, 30.0}) {
buffer.push(t);
}
LLD_CHECK_EQ(*std::ranges::max_element(buffer), 40.0);
LLD_CHECK_EQ(average(buffer), 30.0);
LLD_CHECK(std::ranges::find(buffer, 10.0) == buffer.end());
}
// Strings, so that it->size() means something: "a" has size 1.
// `auto before = it++;` keeps the old position ("a") while `it` moves on
// to "bc"; one more ++ reaches end(). Two default-made iterators (no
// buffer, position 0) compare equal, as forward iterators must.
LLD_TEST(iterators_follow_the_standard_conventions) {
RingBuffer<std::string> buffer{2};
buffer.push("a");
buffer.push("bc");
auto it = buffer.begin();
LLD_CHECK_EQ(it->size(), std::size_t{1});
auto before = it++;
LLD_CHECK_EQ(*before, std::string{"a"});
LLD_CHECK_EQ(*it, std::string{"bc"});
LLD_CHECK(++it == buffer.end());
LLD_CHECK(RingBuffer<std::string>::const_iterator{} == RingBuffer<std::string>::const_iterator{});
}
// LLD_CHECK_THROWS(expression, type) fails unless the expression throws
// an exception of that type. A capacity of 0 must be refused.
LLD_TEST(a_buffer_needs_room_for_one_value) {
LLD_CHECK_THROWS(RingBuffer<int>{0}, std::invalid_argument);
}
  • The two static_asserts check at compile time that the iterator and the buffer meet the C++20 concepts the algorithms rely on. If a required operation were missing, the tests would not compile.
  • iteration_goes_from_oldest_to_newest_before_and_after_a_wrap checks the case the before-version’s first loop got wrong.
  • iterators_follow_the_standard_conventions checks ->, post-increment, reaching end(), and that default-constructed iterators compare equal.

An iterator stays valid only as long as its collection’s rules say it does. Each standard container documents which operations invalidate which iterators: for example, std::vector::push_back invalidates all of them if the vector has to grow (and end() even if it does not), while std::list::push_back invalidates none. Using an invalidated iterator is a bug; for the standard containers it is undefined behaviour.

RingBuffer::push documents the simplest rule: it invalidates every iterator. When the buffer is full, a push moves oldest_, so every position now names a different reading:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// An iterator at the oldest value, 21.5. `auto` here is
// RingBuffer<double>::const_iterator.
auto oldest = readings.begin();
std::cout << "oldest before a push: " << *oldest << '\n';
readings.push(23.0); // invalidates `oldest`
// Using `oldest` here would break the rule push() documents. With this
// implementation it would not crash: it would quietly read 22, the new
// oldest value. Ask again instead:
std::cout << "oldest after a push: " << *readings.begin() << '\n';

The last two lines of the output show the oldest reading changing from 21.5 to 22. An iterator kept across the push would also read 22: a scratch program that did that, built with address and undefined behaviour sanitizers, printed 22 with no error reported. That is the dangerous part. Nothing crashes and no tool complains; the code reads the wrong reading. Here it is not even undefined behaviour, only a logic error (the pointer and the storage are still valid), so no sanitizer can catch it. A rule that is broken silently must be documented where it applies, as push does, and kept simple enough to remember.

Every iterator observes its buffer, so the buffer must outlive it. Range-for is safe even on a temporary, because the loop keeps the range it was given alive until the loop ends:

for (double t : make_readings()) { ... } // fine: the buffer lives for the loop
auto it = make_readings().begin(); // dangles: the buffer is destroyed at the ;

This holds only for the outermost temporary. Before C++23, for (double t : make_station().readings()) dangles if make_station() returns a station by value and readings() returns a reference into it: the station is destroyed before the loop starts.

  • Why only const_iterator? Readings are facts once recorded, and no client needs to change one. A mutable iterator would be a second class with T& instead of const T&, or one class template with a bool parameter for constness. Add it when a client needs it.
  • Why only forward? The clients need one pass, oldest to newest. Because the position is a number, bidirectional (--) and random access (+ n, [n], -, <=>) would be easy to add, together with the matching iterator_category tag, and would let more algorithms run. Add them when needed, and test each.
  • Why not return a copy? A function std::vector<T> in_order() const is simpler, has no invalidation rule, and is often the right choice for small collections. It fails C-1 here: it allocates and copies on every read.
  • Why not a callback? A member for_each(f) that calls f on each reading hides the layout too, with less code. But callers cannot stop early without an extra convention such as returning bool, cannot walk two collections side by side, and cannot use the standard algorithms.
  • You write a collection whose storage order or structure differs from the order callers want: a ring buffer, a tree walked in order, a sparse matrix, a container of containers, a file read in records.
  • Callers should use range-for, standard algorithms, and generic code on it.
  • You want to be free to change the storage later without changing callers.
  • You wrap a standard container and the order is the same. Forward its iterators: auto begin() const { return items_.begin(); }. There is nothing to write.
  • A view says it already. C++20 range adaptors such as std::views::filter and std::views::transform, or a std::span over contiguous storage, often give the order you need without a new iterator class.
  • Callers need only a few values. A newest() or at(i) function is simpler than an iterator.
  • The collection is tiny and rarely read. Returning a copy is simpler and has no invalidation rule.
  • An iterator is a small class with exact rules. Getting ==, post-increment, default construction, and the type names right takes care; the static_asserts above are how you know you have.
  • Invalidation rules are a promise. Once callers rely on “push invalidates everything”, changing the container to keep some iterators valid is easy, but the reverse breaks callers.
  • Iterators observe. A stored iterator is a pointer in disguise, with the same lifetime risks.
  • Exposing the storage as well. A class with a correct iterator and a public storage() gives callers two ways to read, one of them wrong.
  • Storing iterators across changes. Keeping an iterator in a member variable “to resume later” breaks as soon as the collection changes. Store a position or a key, and ask for an iterator again.
  • Claiming a category you do not support. Saying random_access_iterator_tag without it + n that runs in constant time makes algorithms that rely on it slow or wrong.
  • Virtual iterators for speed-sensitive loops. A classic iterator interface with a virtual next() costs a call per element. In C++, use the template conventions unless the collection really is chosen at run time.
  • “Show the newest first.” Callers write std::views::reverse(readings) once the iterator is bidirectional: add prefix and postfix operator--, and change iterator_category to std::bidirectional_iterator_tag. Without the new tag, the concepts still see a forward iterator, and views::reverse does not compile.
  • “Let the display jump to the reading n minutes ago.” Make the iterator random access: it + n, it - other, it[n], and <=>, plus std::random_access_iterator_tag.
  • “Calibrate: subtract 0.5 from every stored reading.” A mutable iterator, or a calibrate(offset) member that does it inside the class. The member is safer: it keeps the rule “readings are not edited by callers”.
  • “Store readings as 16-bit integers to save memory.” Change storage_ and at_position; callers do not change, because none of them sees the storage. (The iterator would return values instead of references, which makes it an input iterator in the C++17 sense; in C++20 terms it can still be a forward iterator. So set iterator_category = std::input_iterator_tag and iterator_concept = std::forward_iterator_tag, and drop operator->, which has no object to point to.)

Exercise: Make the type usable in range-for

  1. An Inventory keeps its items in a private std::vector<Item>. Make for (const Item& item : inventory) work, with as little code as possible.

  2. A Playlist keeps songs in a private std::vector<Song> and the play order in a separate std::vector<std::size_t> of indexes into it, so that “play this next” can move a song without moving the song itself:

    class Playlist {
    public:
    void add(Song song);
    void play_next(std::size_t index); // move song `index` to the front of the order
    private:
    std::vector<Song> songs_;
    std::vector<std::size_t> order_;
    };

    Make range-for visit the songs in play order. Give two answers: one with a C++20 view, one with an iterator class.

  3. What does add do to iterators in your answer to part 2? Write the comment you would put on it.

Show the explained answer

1. The order is the vector’s own, so forward its iterators:

class Inventory {
public:
// Hand out the vector's own iterators. In a const function,
// items_.begin() gives a std::vector<Item>::const_iterator, so
// callers can read the items but not change them.
auto begin() const { return items_.begin(); }
auto end() const { return items_.end(); }
private:
std::vector<Item> items_;
};

No new iterator class is needed. The caller still cannot see or change the vector, because these are const_iterators.

2. With a view: a named function that maps each index in the order to its song.

// A view: a lightweight range that refers to order_ and songs_ rather than
// copying them. As the loop asks for each element, transform calls the
// lambda on the next index in order_ and hands back that song. The
// `-> const Song&` makes the lambda return a reference; without it, the
// lambda would return a copy of each Song.
auto in_play_order() const {
return order_ | std::views::transform(
[this](std::size_t i) -> const Song& { return songs_[i]; });
}
// for (const Song& song : playlist.in_play_order()) { ... }

Do not turn this into begin() and end() by returning in_play_order().begin(): the view would be a temporary, and its iterators refer back to it, so they would dangle. Named as a function, the range-for loop keeps the view alive for the loop, as long as the playlist itself is not a temporary (see Lifetime).

With an iterator class, the same shape as RingBuffer’s:

class Playlist {
public:
class const_iterator {
public:
using iterator_category = std::forward_iterator_tag;
using value_type = Song;
using difference_type = std::ptrdiff_t;
const_iterator() = default;
// Two steps: order_[position_] is the index of the song to play
// at this position, and songs_[that index] is the song itself.
const Song& operator*() const { return list_->songs_[list_->order_[position_]]; }
const_iterator& operator++() { ++position_; return *this; }
const_iterator operator++(int) { auto before = *this; ++*this; return before; }
bool operator==(const const_iterator&) const = default;
private:
friend class Playlist;
const_iterator(const Playlist* list, std::size_t position) : list_{list}, position_{position} {}
const Playlist* list_ = nullptr;
std::size_t position_ = 0;
};
// {this, 0} calls the private constructor; Playlist may, as a friend.
const_iterator begin() const { return {this, 0}; }
const_iterator end() const { return {this, order_.size()}; }
// add, play_next, and the members as before
};
static_assert(std::forward_iterator<Playlist::const_iterator>);

Both versions, after adding “one”, “two”, and “three” and calling play_next(2), visit “three one two”.

3. In the iterator-class version, add appends to both vectors. The iterators hold a pointer to the playlist and a position, not pointers into the vectors, so existing iterators still read valid songs (though references obtained from *it before the add may dangle if songs_ grows); but end() moves, so an end() taken earlier no longer marks the end. The simplest honest comment is the same as push’s:

void add(Song song); // invalidates every iterator

Promising more (“iterators other than end() stay valid”) is true today, but would stop you changing the storage later. In the view version, add may reallocate order_, so its iterators really are invalid.

  • Composite structures are often walked with an iterator, for example a depth-first walk over a folder tree that hides the recursion. See Composite.
  • Visitor separates an operation from the structure it runs on; an iterator decides the order, and a visitor decides what to do with each element. See Visitor.
  • Chain of Responsibility’s list form is a loop over a range of handlers, which is an iterator at work. See Chain of Responsibility.
  • Iterator separates walking a collection from storing it: callers use an iterator’s operations, and never see the layout.
  • In C++, the pattern is a set of conventions (begin, end, *, ++, ==) checked by templates and C++20 concepts, with categories from input to contiguous. Following them makes range-for, algorithms, ranges, and generic code work on your type.
  • Store a logical position in the iterator, offer only the category your clients need, and check the concepts with static_assert.
  • Every iterator observes its collection, and each change to the collection may invalidate it. Document the rule on each function that changes the collection; breaking it can fail silently.
  • Do not write an iterator you do not need: forward a standard container’s iterators, use a view, or return a copy when those are enough.