Random Access Iterator

Category: iterators

Component type: concept

Description

A Random Access Iterator is an iterator that provides both
increment and decrement (just like a Bidirectional Iterator),
and that also provides constant-time methods for moving forward
and backward in arbitrary-sized steps. Random Access Iterators
provide essentially all of the operations of ordinary
C pointer arithmetic.

Models

Notes

[1]
"Equivalent to" merely means that i += n yields the same iterator
as if i had been incremented (decremented) n times. It does
not mean that this is how operator+= should be implemented; in fact,
this is not a permissible implementation. It is guaranteed that i += n
is amortized constant time, regardless of the magnitude of n. [5]

[2]
One minor syntactic oddity: in C, if p is a pointer and
n is an int, then p[n] and n[p] are equivalent. This equivalence
is not guaranteed, however, for Random Access Iterators: only
i[n] need be supported. This isn't a terribly important restriction,
though, since the equivalence of p[n] and n[p] has essentially
no application except for obfuscated C contests.

[3]
The precondition defined in LessThan Comparable is that i
and j be in the domain of operator <. Essentially, then, this
is a definition of that domain: it is the set of pairs of iterators such
that one iterator is reachable from the other.

[4]
All of the other comparison operators have the same domain and
are defined in terms of operator <, so they have exactly the same
semantics as described in LessThan Comparable.

[5]
This complexity guarantee is in fact the only reason why
Random Access Iterator exists as a distinct concept. Every
operation in iterator arithmetic can be defined for
Bidirectional Iterators; in fact, that is exactly what the
algorithms advance and distance do. The distinction is
simply that the Bidirectional Iterator implementations are
linear time, while Random Access Iterators are required to support
random access to elements in amortized constant time. This has
major implications for the sorts of algorithms that can sensibly
be written using the two types of iterators.