An iterator is an interface that can express sequences of unlimited size, such as the range of integers between 0 and Infinity.
It allow a user to loop over every element of a collection (container) while isolating the user from the internal structure of the container.
The Iterator pattern works for a collection of objects that you want to:
The consuming code has only to call on method: the next() method.
Iterators date to the CLU programming language in 1974.
An iterator is behaviorally similar to a database cursor.
They're also complicated, stateful iterators, such as tree traversers.
Iterators are a useful abstraction of input streams that you can see as an infinite iteration.
In procedural languages it is common to use the subscript operator and a loop counter to loop through all the elements in a sequence such as an array.
The use of iterators may have some advantages against indexing:
This is always a trade-off between security (iterators remain always valid) and efficiency. Most of the time, the added security in not worth the efficiency price to pay for it. Using an alternative container (for example a singly linked list instead of a vector) would be a better choice (globally more efficient) if the stability of the iterators is needed.