Conceptually, iterators are consists of five categories:
- input iterator is intended to traverse sequences in the forward direction and provides the read access to the pointed sequence element;
- output iterator is intended to traverse sequences in the forward direction and provides the write access to the pointed sequence element;
- forward iterator is intended to traverse sequences in the forward direction and provides both read and write access to the pointed sequence element;
- bidirectional iterator is intended to traverse sequences in both forward and backward directions and provides the same access to the pointed sequence element as forward iterator;
- random access iterator is similar to bidirectional iterator, but in addition, provides the possibility of arithmetic similar to pointer arithmetic.
The operators ++
and *
are applicable to iterators of all the categories described above.
The operators ==
, !=
and ->
are applicable to iterators of all the categories described above, except the output iterators.
The operator --
is applicable to bidirectional iterators and random access iterators only.
The following possibilities are applicable only to the random access iterators:
- it’s possible to add or subtract an integer to create a random access iterator that points to another element of the sequence;
- it’s possible to subtract one random access iterator from another one to calculate the distance between the two elements of sequence;
- it’s possible to subscript random access iterator by applying the operator
[]
; - it’s possible to compare random access iterators by using any of the following operators:
<
,<=
,==
,!=
,>
,>=
.
Please note, that the calculation of the distance between two non random access iterators is usually much more expensive than subtraction of random access iterators between each other. That’s why the standard library provides the special template function called std::distance
(defined in <iterator>
) for this purpose instead of operator -
.
Finally, please note, that prefix form of operators ++
and --
is usually preferable over the postfix form since the former returns a reference to a modified iterator whereas postfix form is obliged to return a copy of iterator object before incrementing or decrementing and hence likely to be less efficient.