Tools.h++ Manual
13-8 104011 Tandem Computers Incorporated
13
Program output:
much 1
wood 2
a2
if 1
woodchuck 2
could 2
chuck 2
How 1
?1
The problem is to read an input file, break it up into tokens separated by
whitespace, count the number of occurences of each token, and then print the
results. The general approach is to use a dictionary to map each token to its
respective count. Here's a line-by-line description:
1. This is a class used as the value part of the dictionary.
2. A default constructor is supplied that zeroes out the count.
3. We supply a prefix increment operator. This will be used to increment
the count in a convenient and pleasant way.
4. A conversion operator is supplied that allows
Count
to be converted to
an
int
. This will be used to print the results. Alternatively, we could
have supplied an overloaded
operator<<()
to teach a
Count
how to
print itself, but this is easier.
5. This is a function that must be supplied to the dictionary constructor. Its
job is to return a hash value given an argument of the type of the key.
6. Here the dictionary is constructed. Given a key, the dictionary will be
used to look up a value. In this case, the key will be of type
RWCString
,
the value of type
Count
. The constructor requires a single argument: a
pointer to a function that will return a hash value, given a key. This
function was defined on line 5 above.
7. Tokens are read from the input stream into a
RWCString
. This will
continue until an EOF is encountered. How does this work? The
expression "
cin >> token
" reads a single token and returns an
ostream&
. Class
ostream
has a type conversion operator to
void*