



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




In this lesson you will once again use a Vector as an underlying data container, only this time implementing a Map. A Map is an indexed collection class. This means that elements are always provided in a pair consisting of a key and a value. Just as we used a symbolic constant to define the EleType for a vector, we will use two symbolic types to define both the KeyType and the ValueType for our vector. The interface file for this abstraction is shown on the next page. By default, we will use a character pointer for the key, and a double for the value. Insead of the EQ and LE macros used with with the vector, we will have macros for LtKey and EqKey. The Map API is shown near the bottom of the page. When a value is inserted both the key and the value are provided. To search the collection the user provides a key, and the corresponding value is returned. A dictionary that associates words and definitions is a good mental model of a Map. The idea behind the VectorMap is that internally elements in the vector are stored as instances of class Association. The internal class Association stores a key and a value. Each element in the internal Vector is a pointer to an Association: When searching to see if there is an entry with a given key, for example, each element of the vector is examined in turn. The key is tested against the search key, and if it matches the element has been found. A similar approach is used to delete a value. A loop is used to find the association with the key that matches the argument. Once the index of this association is found, the Vector remove operation is used to delete the value. Elements in a map must have unique key. Within the method put one easy way to assure this is to first call containsKey , and if there is already an entry with the given key call remove to delete it. Then the new association is simply added to the end. struct association { KeyType key; ValueType value; };
void vectorMapPut (struct vector *vec, KeyType key, ValueType val) { struct association * ap; if (vectorMapContainsKey(vec, key)) vectorMapRemove(vec, key); ap = (struct association *) malloc(sizeof(struct association)); assert(ap != 0); ap->key = key; ap->value = val; vectorAdd(vec, ap); } To extract a value you use the function get. Rather than return the association element, this function takes as argument a pointer to a memory address where the value will be stored. This technique allows us to ignore an extra error check; if there is no key with the given value the function should do nothing at all. void vectorMapGet(struct vector *vec, KeyType key, ValueType *valptr); Based on your implementation, fill in the following table with the algorithmic execution time for each operation: