Последним примером контейнерного класса является ассоциативный массив, представленный классом Dictionary. Он позволяет хранить объекты и получать доступ к ним по произвольному ключу (например, объекту класса String).

Для организации этого класса также используется хеш-таблица.

оI

class Dictionary : public Object {
struct Hashltem {
Hashltem * next; // pointer to next item in chain
Object * key; // key object
Object * data; // object being stored
long hashValue; // hash value if the key
};
private:
Hashltem ** hashTable; // hash table
int hashSize;
// table contains hashSize elements int numltems;
// # of items currently in the dictionary
static MemoryPool pool; // pool of Hashltems public:
class Iterator // dictionary iterator
{
private:
const Dictionary * diet;
// dicitonary we're iterating on

Объектная модель. Основные классы

int hashlndex; // index into hash table
Hashltem * item; // current hash item
public:
Iterator ( const Dictionary * ); Object * key () const
return item -> key;
Object * value () const
return item -> data;
bool end () const
return hashlndex >= diet -> hashSize;
void operator ++ ();
};
friend class Iterator;
Dictionary ();
Dictionary ( const Dictionary& theDict );
Dictionary ( const char * theName, int theHashSize = 1000 ) ; -Dictionary ();
virtual bool isOk () const {
return hashTable != NULL && hashSize > 0;
}
virtual int compare ( const Object * obj ) const;
virtual long hash () const {
return numlterns;
}
bool operator == ( const Dictionary^ diet ) const {
return compare ( kdict ) == 0;
}
bool operator != ( const Dictionaryfc diet ) const
return ! operator -= ( diet ) ;
Object * itemForKey ( const Objects key ) const // return item for given key on NULL
return itemForKey ( &key );
void removeObject ( const Objects key )
removeObject ( &key );
Object * itemForKey ( const Object * key ) const;

⇐ Предыдущая| |Следующая ⇒