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("color","blue"); nvp.setValue("number","one"); nvp.setValue("automobile","car"); nvp.setValue("dwelling","house"); nvp.setValue("parent","dad"); // print the dictionary stdoutput.write("Current contents:\n"); nvp.write(); stdoutput.write('\n'); // replace some values nvp.setValue("number","two"); nvp.setValue("dwelling","apartment"); nvp.setValue("parent","mom"); // remove a value nvp.remove("color"); // print the dictionary stdoutput.write("Current contents:\n"); nvp.write(); stdoutput.write('\n'); // clear the dictionary nvp.clear(); // set some new values nvp.setValue("road","highway"); nvp.setValue("furniture","chair"); nvp.setValue("tree","elm"); // 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 print() method works for primitive types and strings, but for more compex types, it only prints out the address of the object.
Note also that the dictionary class does not manage the data stored in it. If you store a list of dynamically allocated strings or objects, they will not be deleted when a node is removes or when the list is cleared. The recommended method for removing a node is to detach the node, delete its dynamically allocated members and then delete the node.
#include <rudiments/dictionary.h> #include <rudiments/stdio.h> int main(int argc, const char **argv) { // create a dictionary of name-value pairs dictionary<char *,char *> nvp; nvp.setManageArrayKeys(true); nvp.setManageArrayValues(true); // set some name-value pairs nvp.setValue(charstring::duplicate("color"), charstring::duplicate("blue")); nvp.setValue(charstring::duplicate("number"), charstring::duplicate("one")); nvp.setValue(charstring::duplicate("automobile"), charstring::duplicate("car")); nvp.setValue(charstring::duplicate("dwelling"), charstring::duplicate("house")); nvp.setValue(charstring::duplicate("parent"), charstring::duplicate("dad")); // print the dictionary stdoutput.write("Current contents:\n"); nvp.write(); stdoutput.write('\n'); // remove a value nvp.remove((char *)"color"); // print the dictionary stdoutput.write("Current contents:\n"); nvp.write(); stdoutput.write('\n'); // clear the dictionary nvp.clear(); }