next up previous
Next: About this document Up: Using the hush ADT's Previous: Ordered lists

Dictionaries

A dictionary is a mapping between strings (char*) and some (user-defined) type. An instance of a type is stored with a string as `index' and retrieved with that string. Dictionaries are very handy for storing objects by tags. The example should speak for itself.

The example:

// dictionary.cc

#include <hush/dictionary.h>
#include <hush/string.h>
#include <iostream.h>

// define our own class which can be used in the dictionary
class myclass
{
public:
    myclass(int i) { i_ = i; }
    int value() const { return i_; }

private:
    int i_;
};


int main()
{
    myclass a(27), b(3), c(72);         // create some instances of myclass

    dictionary<myclass> dict;           // create an empty dictionary that
                                        // will contain instances of myclass

// store some objects (only POINTERS are stored!)
    dict["foo"] = &a;
    dict["bar"] = &b;
    dict["cow"] = &c;

    if (!dict["apple"]) 
        cout << "no such thing" << endl;

    dict["apple"] = &c;
    dict["car"]   = &b;
    dict["event"] = &a;

    myclass* mcptr1 = dict["foo"];
    myclass* mcptr2 = dict["bar"];

// retrieve some objects by name:
    cout << "foo: " << mcptr1 -> value() << endl;
    cout << "bar: " << mcptr2 -> value() << endl;

// print the complete dictionary:
    iter<string> it = dict;             // create an iterator over strings
    string* strptr = 0;                 // pointer to myclass for iteration
    myclass* mcptr = 0;

    while(strptr = it())
    {
        mcptr = dict[*strptr];
        cout << *strptr << " = " << mcptr -> value() << endl;
    }

    return 0;
}



SE Praktikum
Tue Aug 13 13:18:42 MET DST 1996