Tools.h++ Manual
17-8 104011 Tandem Computers Incorporated
17
The default definition (comparing the addresses of the two objects) should
really be thought of as a placeholder—in practice, it is not very useful and
could vary from run-to-run of a program.
Here is an example that uses
compareTo()
as well as
isEqual()
and
hash()
.
RWCollectableString a(“a”);
RWCollectableString b(“b”);
RWCollectableString a2(“a”);
a.compareTo(&b); // Returns -1
a.compareTo(&a2); // Returns 0 (“compares equal”)
b.compareTo(&a); // Returns 1
a.isEqual(&a2); // Returns TRUE
a.isEqual(&b); // Returns FALSE
a.hash() // Returns 96 (operating system
dependent)
Note – the
compareTo()
function for
RWCollectableStrings
has been
defined to compare strings lexicographically in a case sensitive manner. See
“RWCString” on page 72 in Chapter 21, “Class Reference” for details.
Here is a possible definition of
compareTo()
for our example:
int Bus::compareTo(const RWCollectable* c) const
{
const Bus* b = (const Bus*)c;
if (busNumber_ == b->busNumber_) return 0;
return busNumber_ > b->busNumber_ ? 1 : -1;
}
Here, we are using the bus number as a measure of the ordering of busses.
Hence, were a group of busses to be inserted into a
RWBinaryTree
, they
would be sorted by their bus number.