Stacks, queues, dynamic arrays, and linked lists are all examples of collection types, which is to say that their purpose in life is to manage groups of other objects. Often, we will want to perform similar operations on all collections, e.g.:
- iterating over all items in a collection
- performing union or intersection of one collection with another
- filtering the elements in a collection based on some predicate
In light of what we know about inheritance, it becomes natural to ask: can we define a superclass for all collections, in order to enforce a common interface on (e.g.) linked lists and dynamic arrays?
Iterators
Consider the difference between iterating over a linked list and iterating over a dynamic array:
// linked list iteration for (Node * cur = head; cur != NULL; cur = cur->next) // do stuff // array iteration for (int i = 0; i < length; i++) // do stuff In each case, iteration takes 3 essential components:
- an initializer
- a predicate for continuation
- an update expression
We can use a pair of parallel inheritance heirarchies to abstract the idea of iteration from any particular container class...
![]()