Note that the objects compared by TMOrderableCollectibleComparator must descend from MOrderableCollectible. In addition to defining an IsEqual member function, orderable collectible objects must define protocol for IsLessThan and IsGreaterThan. The basic algorithm for TMOrderableCollectibleComparator::Compare looks something like this.
if (leftObject->IsEqual(rightObject)) return kEqual; if (leftObject->IsLessThan(rightObject)) return kLessThan; else return kGreaterThan;
The following program should clarify the use of ordered comparators with sorted sequences.
Sample program
using a comparator
for sorted sequences
of text
The output shows lexical sorting based on calls by the ordered comparator to member functions of TStandardText (IsEqual, IsLessThan, IsLessThan). // Copyright (c) 1994 Taligent, Inc. All Rights Reserved.
#ifndef Taligent_STANDARDTEXT
#include <StandardText.h>
#endif
#ifndef _H_STDIO
#include <stdio.h>
#endif
void printCollection(TCollectionOf<TStandardText>* collection)
{
int i = 0; // tracks order of elements
TIteratorOver<TStandardText>* iterator = collection->CreateIterator();
for (TStandardText* text = iterator->First();
text != NIL;
text = iterator->Next(), i++) {
////////////////////////////////////////////////////
// buffer must be large enough for
// longest possible string + zero terminator
////////////////////////////////////////////////////
static const int kBufferSize = 256;
static char extractBuffer[kBufferSize];
text->Extract(TTextRange::GetMaximumRange(),
extractBuffer,
kBufferSize - 1);
printf("\n%3d> %s", i, extractBuffer);
}
printf("\n");
delete iterator;
}
int main()
{
TMOrderableCollectibleComparator<TStandardText>* comparator =
new TMOrderableCollectibleComparator<TStandardText>();
TSortedSequenceOf<TStandardText>* collection =
new TSortedSequenceOf<TStandardText>(comparator, NIL);
collection->Add(new TStandardText("one"));
collection->Add(new TStandardText("two"));
collection->Add(new TStandardText("three"));
collection->Add(new TStandardText("one"));
collection->Add(new TStandardText("two"));
collection->Add(new TStandardText("three"));
printCollection(collection);
delete collection;
return 0;
}
0> one 1> one 2> three 3> three 4> two 5> two