Hash functors and equalitors – HP Integrity NonStop J-Series User Manual

Page 124

Advertising
background image

Click on the banner to return to the user guide home page.

©Copyright 1996 Rogue Wave Software

Hash Functors and Equalitors

The associative hash-based templates use a hash function object to determine how to place and
locate objects within the collection class. An advantage of using hash function objects is efficient,
constant-time retrieval of objects. A disadvantage is that objects are maintained in an order
determined by mapping the result of the hash function onto the physical layout of the collection
class itself. Rarely does this ordering have a useful meaning beyond the internal machinations of the
hash-based container.

To avoid complete chaos, associative hash-based containers make use of an equality object.
Collections which allow multiple keys that are equivalent to one another use the equality object to
ensure that equivalent objects are grouped together when iteration through the container occurs.
Hash collections which do not allow multiple keys use the equality object to ensure that only unique
items are admitted. To effect these procedures, we need two template arguments in addition to the
type or types of the elements being collected: a hash functor, and an equalitor.

A hash functor is a class or struct that contains a function-call operator that takes a const reference
to a potential element of the collection class, and returns an unsigned long hash value. An equalitor
is a class or struct that contains a function-call operator that takes two potential elements of the
collection class, and returns true if the elements should be considered equivalent for the purpose of
grouping objects or ensuring uniqueness within the collection class. For example:

#include <rw/tvhset.h> // contains RWTValHashSet
#include <rw/cstring.h> // Contains RWCString
struct StringHash {
unsigned long operator()(const RWCString& s)
{ return s.hash(); }
};
struct StringEqual {
unsigned long operator()(const RWCString& s, const RWCString& t)
{ return s == t; }
};
RWTValHashSet<RWCString, StringHash, StringEqual> rwhset;

Here we instantiate an RWHashValSet of

RWCString

s with our own hash functor and equalitor.

The example shows the relative ease of creating these structs for use as template arguments.

Advertising
This manual is related to the following products: