CKTIS / C++
Iterators and generators
An iterator describes a position and how to traverse a sequence, while a generator produces its elements on demand. Learn about half-open ranges, sentinels, iterator categories, and the single-pass std::generator from C++23.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
auto it = range.begin();
auto last = range.end();
for (; it != last; ++it) { /* use *it */ }
std::generator<int> sequence() { co_yield 1; }An iterator generalizes a pointer: it lets algorithms traverse different data structures without knowing their representation. At a valid position, *it accesses an element and ++it advances the iterator. The range [first, last) includes its beginning but excludes its end. last is a sentinel and may have a different type from the iterator. Do not dereference the end position.
Categories specify supported operations and guarantees. An input iterator supports reading, while an output iterator supports writing a compatible type through *it = value; not every iterator supports both. forward_iterator adds a multipass guarantee, bidirectional_iterator backward movement, random_access_iterator constant-time jumps and distance calculations, and contiguous_iterator additionally guarantees contiguous element storage.
A generator is not a position: it is a source of a sequence exposed through an iterator. C++23's std::generator from <generator> is a lazy, coroutine-based input range; co_yield makes the next element available. It is single-pass: do not call begin() again on the same object. Do not use its iterator after destroying the generator.
In the example, values keeps the generator alive, begin() starts computation up to the first element, and ++it resumes it until the next element or completion. The output is three lines: 1, 4, 9. A library implementation supporting <generator> is required; the C++23 flag alone does not establish that support. The supplied site hosts an evolving standard draft, not frozen C++23 wording; production-runtime compatibility has not been attested.
Examples
#include <generator>
#include <iostream>
std::generator<int> squares() {
for (int n = 1; n <= 3; ++n) {
co_yield n * n;
}
}
int main() {
auto values = squares();
auto it = values.begin();
auto last = values.end();
for (; it != last; ++it) {
std::cout << *it << '\n';
}
}
Result
1 4 9
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.