a firstworks project
Rudiments
About Documentation Download Licensing News

Using the dictionary class

The dictionary class allows you to store arbitrary numbers of key/value-pair data.

Each dictionary is composed of a set of dictionarynodes. Each dictionarynode contains the key and value.

#include <rudiments/dictionary.h>
#include <rudiments/stdio.h>

int main(int argc, const char **argv) {

	// create a dictionary of name-value pairs
	dictionary<const char *,const char *>	nvp;

	// set some name-value pairs
	nvp.setValue("dog","mammal");
	nvp.setValue("eagle","bird");
	nvp.setValue("snake","reptile");
	nvp.setValue("frog","amphibian");
	nvp.setValue("trout","fish");

	// print the dictionary
	stdoutput.write("Current contents:\n");
	nvp.write();
	stdoutput.write('\n');

	// replace some values
	nvp.setValue("eagle","raptor");
	nvp.setValue("frog","poison dart frog");
	nvp.setValue("trout","freshwater fish");

	// remove a value
	nvp.remove("dog");

	// print the dictionary
	stdoutput.write("Current contents:\n");
	nvp.write();
	stdoutput.write('\n');

	// clear the dictionary
	nvp.clear();

	// set some new values
	nvp.setValue("cat","mammal");
	nvp.setValue("parrot","bird");
	nvp.setValue("turtle","reptile");

	// print out the dictionary a different way
	stdoutput.write("Current contents:\n");
	linkedlist<const char *>	*keys=nvp.getKeys();
	for (listnode<const char *> *kn=keys->getFirst();
						kn; kn=kn->getNext()) {
		stdoutput.printf("%s=%s ",
			kn->getValue(),nvp.getValue(kn->getValue()));
	}
	delete keys;
	stdoutput.write('\n');
}

Since the dictionary class is template-based, it can store any type of data.

Note that the write() method works for primitive types and strings, but for more complex types, it only prints out the address of the object.

Note also that, by default, the dictionary class does not manage the data stored in it. If you store dynamically allocated strings or objects, they will not be deleted automatically when a node is removed or the dictionary is cleared. However, if setManageKeys(true) or setManageValues(true) is called, then keys or values will be deleted (using delete) when a node is removed or the dictionary is cleared or destroyed. If setManageArrayKeys(true) or setManageArrayValues(true) is called, then keys or values will be deleted using delete