Title: Mapping Functions and Iterators
1Mapping Functionsand Iterators
Eric Roberts CS 106B October 30, 2009
2Where Are We Now?
- In our last episode, we implemented the generic
Map class based on the idea of a hash table.
- Our implementation had all of the features of the
library version of Map with the exception of any
strategy for iterating through the keys in a map.
- The goal for today is to look at two strategies
that implement iteration - Mapping functions
- Iterators
- The foreach facility we have used in this course
is syntactic sugar for the iterator-based
approach. Unfortunately, the details of the
foreach implementation are beyond the scope of
this course.
3The von Neumann Architecture
- One of the foundational ideas of modern
computingtraditionally attributed to John von
Neumann although others can make valid claims to
the ideais that code is stored in the same
memory as data. This concept is called the
stored programming model. - If you go on to take CS 107, you will learn more
about how code is represented inside the
computer. For now, the important idea is that
the code for every C function is stored
somewhere in memory and therefore has an address.
4Function Pointers in C
- As C did before it, C makes it possible for
programmers to use function pointers explicitly.
- The syntax for declaring function pointers is
consistent with the syntax for other pointer
declarations, although it takes some getting used
to. Consider the following declarations
5Exercise Plotting a Function
Write a function Plot that takes a function
(double ? double) as a parameter along with the
limits of the domain and range and then plots
that function on the graphics window.
6Exercise Two Related Questions
Hint In the time that x moves from minX to
maxX, sx must move from 0 to GetWindowWidth() y
must move in the opposite direction from
GetWindowHeight() to 0.
7Mapping Functions
- The ability to work with pointers to functions
offers one solution to the problem of iterating
through the elements of a map. All you need to
do is specify a function that can be applied to a
given element and then have the implementation of
the Map class apply that function to each element
in turn.
8Exercise Implement mapAll
Implement the simple version of
void mapAll(void (fn)(string))
as part of the Map class.
9The Bucket Hash Structure
0
1
2
3
4
5
6
SD
NE
MO
MA
HI
South Dakota
Nebraska
Missouri
Massachusetts
Hawaii
null
10Passing Values and Keys Together
- Suppose, however, that myMap is a Mapltintgt and
that you want to print the keys and the values
together. You could not achieve that goal with
the current definition of mapAll because there is
no way for the PrintKey function to get access to
the values or even to the map itself.
11Passing Data to Mapping Functions
- Even this change, however, is not sufficient to
write anything at all complicated using the
mapping function approach. In almost all cases,
you need to pass additional information to the
mapping function. That data must pass from the
client, through the implementation, and back into
the function the client supplied. For this
reason, these functions are often referred to as
callback functions.
12Exercise Find Longest State Name
Suppose that you have a Mapltstringgt named
stateNames that maps two-letter abbreviations
into state name pairs. Write a function that
returns the longest state name in the map. This
function, of course, is easy to write using
foreach the idea in this problem is to use
mapping functions to do the same thing.
13Iterators
- Hardly anyone today uses mapping functions in
practice because they have been superseded by
iterators, which are far more convenient to use.
- The CS106 collection classes each define a nested
class called Iterator that maintains enough state
to sequence through the elements of the
collection in order.
- The next few slides describe a couple of
strategies for implementing iterators, and the
final slide shows how those strategies can be
used to create an iterator for the Map class.
14Offline vs. Online Iterators
- One simple way to implement an iterator is to
adopt the following strategy - Create an empty vector of the same element type.
- Use a mapping function to store each element in
the vector. - Store the vector and current index in the
iterator object. - Implement next() by returning the current element
and then advancing the index. - Implement hasNext() by checking if the index is
past the end of the vector. - Such an iterator is called an offline iterator.
- Offline iterators tend to be easy to write, but
the fact that they have to precompute the entire
list of elements makes them too inefficient to
use in practice. - The online iterator model keeps enough state
information in the iterator so that
precomputation is not required.
15The MapIterator Class Definition
16Prototype for the iterator Method
17Implementing MapIterator
/ Implementation notes Iterator
constructors ----------------------------------
--------- The Iterator class has two
constructors. The public constructor is
required so that clients can declare variables of
this type. The private constructor is called
by the iterator method in the Map class.
/ template lttypename ValueTypegt MapltValueTypegt
IteratorIterator() mp NULL template
lttypename ValueTypegt MapltValueTypegtIteratorIte
rator(Map mp) this-gtmp mp cp
NULL bucketIndex -1
advanceToNextCell() template lttypename
ValueTypegt typename MapltValueTypegtIterator
MapltValueTypegtiterator() return
Iterator(this)
18Implementing MapIterator
/ Implementation notes Iterator
constructors ----------------------------------
--------- The Iterator class has two
constructors. The public constructor is
required so that clients can declare variables of
this type. The private constructor is called
by the iterator method in the Map class.
/ template lttypename ValueTypegt MapltValueTypegt
IteratorIterator() mp NULL template
lttypename ValueTypegt MapltValueTypegtIteratorIte
rator(Map mp) this-gtmp mp cp
NULL bucketIndex -1
advanceToNextCell() template lttypename
ValueTypegt typename MapltValueTypegtIterator
MapltValueTypegtiterator() return
Iterator(this)
19Implementing MapIterator
/ Implementation notes hasNext, next
----------------------------------- Each of
these methods assumes that the internal state of
the iterator has been set by a call to
advanceToNextCell so that cp indicates the
next key to return, or NULL at the end of
iteration. / template lttypename
ValueTypegt bool MapltValueTypegtIteratorhasNext(
) if (mp NULL) Error("hasNext called on
uninitialized iterator") return cp !
NULL template lttypename ValueTypegt string
MapltValueTypegtIteratornext() if (mp
NULL) Error("next called on uninitialized
iterator") if (!hasNext())
Error("Attempt to get next from iterator where
hasNext() is false") string result
cp-gtkey advanceToNextCell() return
result
20The End