Maps in C
This C code demonstrates the implementation of a simple map (associative array) data structure. Here’s an explanation of the key points:
We define a
KeyValue
struct to represent key-value pairs and aMap
struct to hold the collection of pairs.The
makeMap
function creates an empty map.setKeyValue
adds or updates a key-value pair in the map.getValue
retrieves a value for a given key, with a boolean flag to indicate if the key was found.deleteKeyValue
removes a key-value pair from the map.clearMap
removes all key-value pairs from the map.printMap
is a utility function to display the contents of the map.In the
main
function, we demonstrate various operations on the map:- Creating an empty map
- Setting key-value pairs
- Retrieving values
- Checking the length of the map
- Deleting a key-value pair
- Clearing the map
- Checking for the existence of a key
Note that this implementation is a simplified version and doesn’t include some of the more advanced features of Go’s maps, such as built-in iteration or thread-safety. In a real-world C program, you might want to use a more sophisticated hash table implementation for better performance and additional features.
To compile and run this program:
This output demonstrates the various operations performed on the map, similar to the Go example.