Programming and Introductory Data Structures
So far, we've looked at several different kinds of abstractions:
Abstract data types
Today, we'll talk about what happens when containers and
functional abstraction meet.
Several weeks ago, we talked about a collection of abstract data
a subtype of an
was just like an
, with one additional
// REQUIRES: set is non-empty
// EFFECTS: returns the largest element
walked down the set of integers, computing the maximum.
works, it is unsatisfactory since there are many
computations that could be performed on a set of integers.
As ADT designers, we have at least two choices:
Predict all of a client's needs, and provide a method for each of
(Sum, min, max, .
Provide an abstraction that can access
object in the set, with
The second is preferable and is called an "iterative abstraction", or
commonly an "iterator" because it allows clients to iterate over
the members of some container.
In principle, any container class could support an iterator.
An iterator is a
abstraction from the container
There are two reasons why this is so:
An iterator's lifetime is shorter than its container's: the
container must exist before you iterate over its contents, and
the container can't be destroyed safely before the iterator is.
A container can have more than one "live" iterator at a time.
So, iterators are a
abstract data type.
Usually, for each container type one has, there is also (at
least) one iterator type defined.
An iterator has the following operations:
: create a new iterator, bound to some particular
instance of a container class.
Once an iterator is created, the underlying container cannot be
modified in any way, else the iterator is invalid.
The intuition behind this is that the iterator depends on the
representation of the container – if that changes, the iterator is
likely to miss an element or return an element that no longer
In general, an iterator makes no guarantee about the order in
which objects are returned, though it is possible to define
specific iterators with such a guarantee (like when working with