A class random_access_iterator that satisfies the requirements of a random access iterator for the value type T, supports the following operations in addition to the operations supported by a bidirectional iterator.
We promised to show why a pointer (in this case V*) is a random access iterator. In order to show that it supports the required operations, we give a program that uses them. Not all operations are used - so it is not a complete proof - but hopefully enough to convince the reader.
Notice that the program is nothing special. It was valid C++ (with minor changes even valid C), long before the iterator concept was invented! The comments point to the requirements.
const int N = 10; struct V { float val; }; float fill_and_add(V *b, V *e) { V *c; /* creation, first way (ForwardIterator) */ float sum; for (int i=0; i<e-b; i++) /* subtraction (RandomAccessIterator) */ b[i].val = i*i/2.0; /* indexing (RandomAccessIterator) */ for (c=b; c != e; ++c) /* assignment, inequality test, increment (ForwardIterator) */ sum += (*c).val; /* dereference (ForwardIterator) */ return sum; } float foo() { V a[N]; V *e(a+N); /* creation, second way (ForwardIterator) and */ /* integer adding (RandomAccessIterator) */ return fill_and_add(a,e); }
We give a second example for the more advanced STL user. We stated that iterators allow us to work with different data structures in a unform manner. But the function fill_and_add in the previous example only takes pointers as argument. Here we rewrite it so that it takes any random access iterator as argument, provided it has the right value type (V).
template <class RandomAccessIterator> float fill_and_add(RandomAccessIterator b, RandomAccessIterator e) { RandomAccessIterator c; float sum; for (int i=0; i<e-b; i++) b[i].val = i*i/2.0; for (c=b; c != e; ++c) sum += (*c).val; return sum; }