An iterator provides sequential access to elements without exposing how a collection stores them. It lets one algorithm process arrays, vectors, linked lists, or maps through a common interface. section 11.1 section 11.1.3
The design problem appears when one report must process teams whose Player objects are stored differently. Without an iterator, the report becomes coupled to each collection representation. Refactoring moves traversal into collection-specific iterator classes. section 11.1 section 11.1.3
A typical iterator design separates responsibilities:
- Define a common Iterator interface with next() and has_next(). section 11.1.3
- Store a private cursor in each concrete iterator; represent it as an array index, vector iterator, or map iterator. section 11.1.3
- Let each collection create the iterator appropriate for its representation. section 11.1.3
- Have the client repeatedly test has_next(), retrieve the current element with next(), and let the iterator advance. section 11.1.3
Reporting baseball teams
Team 1 stores players in an array, Team 2 in a vector, and Team 3 in a map. TeamReport requests an iterator from each Team and prints every player's student ID and name without accessing the underlying collection. Adding or changing a sequential collection can therefore avoid changes to the reporting algorithm. section 11.1 section 11.4
Figure 11.2 Each Team subclass creates an iterator that is appropriate for its sequential collection of Player objects. Class TeamReport delegates iterating over the various forms of sequential collections to the Iterator subclasses. Each Iterator subclass knows how to iterate over its form of sequential collection and has a private cursor member variable to keep track of the current Player object. Class TeamReport does not know how each Team subclass stores its sequence of Player objects, and therefore, it is loosely coupled from the Team subclasses. The grayed-out portions of the diagram haven’t changed logically from figure 11.1.
Shows how collection subclasses create representation-specific iterators while the client delegates traversal and remains loosely coupled. section 11.1.3














