Site icon Learn C++

Categories of Iterators in C++

sea washing sandy seaside in resort

Photo by Ben Mack on Pexels.com

Conceptually, iterators are consists of five categories:

  1. input iterator is intended to traverse sequences in the forward direction and provides the read access to the pointed sequence element;
  2. output iterator is intended to traverse sequences in the forward direction and provides the write access to the pointed sequence element;
  3. forward iterator is intended to traverse sequences in the forward direction and provides both read and write access to the pointed sequence element;
  4. 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;
  5. 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:

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.

Exit mobile version