Why are iterators better than indexes?
- In the cases where index is not available (like with std::list, for
example).
- In the case where a generic function accepting an iterator
is called.
- When writing a function template that is supposed to work with
more than one container type.
- They exist to create uniformity among all containers and ability to use
all containers' iterators as well as regular pointers in all standard
algorithms.
- Iterators can point to sequences that don't exist except as a concept.
For instance, you can make an iterator class that steps through prime
numbers without actually having to build a container of primes.
However, if ignoring container types that do not support random access (list, set, etc.), iterators still offer
- Pointer like semantics (think of string::iterator vs. char *).
- Generalized concept usable beyond iteration over elements inside a
container.
- Better performance than container member functions in a few cases.