CN_Map
Synopsis
CN_Map (Clara Nguyen's Map) is a generic associative data structure
that gives C programmers a way to store data in key/value pairs. It
is an implementation of the self-balancing Red-Black Tree.
In CN_Maps, users are able to store any type they wish for both
keys and values. Key values are sorted and must be unique.
What to include
Include the following files in your project:
#include "cn_cmp.h"
#include "cn_map.h"
Unlike other CNDS libraries, this one recommends the inclusion of 2
files:
- cn_map.h has the definitions for the CN_Map.
- cn_cmp.h includes comparison utility functions that
can be used to sort keys.
Datatypes added
CN_Map is a
library. It adds structs, typedefs, and functions
that users are able to use. Here are what it contains:
Typedefs
- CNM_UINT = unsigned int
- CNM_U64 = unsigned long long
- CNM_BYTE = unsigned char
- CNC_COMP = int
Structs
- CN_MAP = The actual CN_Map itself. This is a pointer type to
struct cn_map
, so all functions pass pointers rather than copies.
- CNM_ITERATOR = CN_Map iterator used to traverse the map.
- CNM_NODE = Node that holds a key/value pair in the CN_Map
Enums
- CNM_COLOUR = Colour of a node. Defined as
[ CNM_RED, CNM_BLACK, CNM_DOUBLE_BLACK ]
Besides constructors, All "cn_map" functions take a "CN_MAP" data type
in front of it. This may be misleading at first, since CN_MAP is
actually a pointer type. So function calls do not copy the data
structure. Do note this if you decide to expand on this library.
Why the typedefs? If I need to make a hotfix on types in this library,
it'd be a single line of code changed.
Container Properties
-
Associative - Elements are accessed by their key,
which can be any type defined by the user.
-
Sorted - Elements in CN_Maps are sorted based on a
user-given comparison function. When iterated through, keys
will always be in order.
-
Dynamic - Users can specify custom destructor and
sorting functions which are called at various times during
the CN_Map's lifetime.
-
Generic - Despite C lacking templates, CN_Map allows
the user to specify the data types for both the key and
value.
Download
Grab it from GitHub, here:
https://github.com/iDestyKK/CN_Map
Example Usage
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cn_cmp.h"
#include "cn_map.h"
main() {
CN_MAP map = cn_map_init(char, int, cn_cmp_char);
char key;
int value;
//Put in a-z with 0-25 in as key/value pairs.
for (key = 'a', value = 0; key <= 'z'; key++, value++) {
cn_map_insert(map, &key, &value);
}
//Iterate through
CNM_ITERATOR it;
for (cn_map_begin(map, &it); !cn_map_at_end(map, &it); cn_map_next(map, &it)) {
printf(
"%c -> %d\n",
cn_map_iterator_key (&it, char),
cn_map_iterator_value(&it, int)
);
}
}