Logo Data Structures and Algorithms with Object-Oriented Design Patterns in C++
next up previous contents index

Hashing Containers

The Container class which was defined in Section gif, abstracts the notion of an object which contains other objects. The Container class is derived from the Object class and, therefore, it has a member function called Hash. What is a suitable hash function for a container?

Given a container c which contains n objects, tex2html_wrap_inline62766, tex2html_wrap_inline62766, ..., tex2html_wrap_inline62770, we can define the hash function f(c) as follows:

  equation11581

I.e., to hash a container, simply compute the sum of the hash values of the contained objects.

Program gif shows the implementation of the Container::Hash function. This function makes use of the Accept function to cause a special visitor, HashingVisitor, to visit all of the objects contained in the container. When the HashingVisitor visits an object, it calls that object's Hash function and accumulates the result.

   program11592
Program: Container Class Hash Member Function Definition

Since the Accept function is a virtual member function which is defined in the Container class. We assume that all classes derived from the Container class will provide an appropriate implementation for Accept. Note that it is not necessary for any derived class to redefine the behavior of the Hash member function--the behavior inherited from the Container class is completely generic and should suffice for all concrete container classes.

There is a slight problem with Equation gif. Different container types that happen to contain identical objects produce exactly the same hash value. E.g., an empty stack and an empty list both produce the same hash value. We have avoided this situation in Program gif by adding to the sum the value obtained from hashing the name of the container itself.


next up previous contents index

Bruno Copyright © 1997 by Bruno R. Preiss, P.Eng. All rights reserved.