Adventures in Data Structures Vol 14: Dictionaries
Introduction to Dictionaries
The last ADT that we will be discussing in this class is the dictionary or the map.
Dictionaries are pretty common data structures since a common situation that arises is if we want to store key-value pairs. In C, this can be defined using a struct like:
The dictionary stores these key-value pairs and allows for quick look up of values using their associated keys.
The operations which a dictionary supports is:
- void put(key, value)
- void get(KT key, VT *ptr)
- int containsKey(KT key)
- void removeKey(KT key)
We can implement a dictionary in C using a dynamic array where each element is a pointer to an association struct we defined above:
Function Implementations
The get
function finds the value associated with a key and puts that value inside of a pointer variable called valptr
.
The put
function places a value in the position associated with a particular key.
If an association is already there with that key, it is removed.
The contains
function is also very helpful.
Finally, let’s implement the remove
function.