diff options
author | Tucker Evans <tucker@tuckerevans.com> | 2020-07-06 15:39:08 -0400 |
---|---|---|
committer | Tucker Evans <tucker@tuckerevans.com> | 2020-07-08 10:56:36 -0400 |
commit | cf427c05b05e0409cfdeb6bc30b69070dd1700c3 (patch) | |
tree | 65f706850bc4e5c56889a11eba67bc092c60d778 | |
parent | f652c23fbc61dec9db48c6e745edca5a12b655bb (diff) |
Add constructor for maps
-rw-r--r-- | collections/map/map.adoc | 22 | ||||
-rw-r--r-- | collections/map/map.c | 16 | ||||
-rw-r--r-- | collections/map/map.h | 3 |
3 files changed, 40 insertions, 1 deletions
diff --git a/collections/map/map.adoc b/collections/map/map.adoc index a43ae1d..fc6b8b7 100644 --- a/collections/map/map.adoc +++ b/collections/map/map.adoc @@ -1,7 +1,7 @@ Map === Tucker Evans -v0.0, 2020-07-06 +v0.1, 2020-07-06 A basic map implemented in an AVL tree. @@ -30,3 +30,23 @@ first parameter. This is a pointer to a function that to compare keys from pointers. This typedef is provided to cast comparison functions as a map expects the comparison function to take void* as its parameters. + +Functions +--------- +[[map_new]] ++map_new(cmp_func cmp)+ +~~~~~~~~~~~~~~~~~~~~~~~ +Constructs an empty map. ++cmp+ should be a function that takes two pointers (+lhs+, +rhs+)to your value +type and returns (int) a negative value if +lhs+ is less than +rhs+, zero if ++lhs+ is equal to +rhs+, and positive value if +lhs+ is greater than +rhs+. + +Examples +^^^^^^^^ +[source,c] +---- +#include "map.h" +#include <string.h> + +map *dict = map_new((cmp_func) strcmp); +---- diff --git a/collections/map/map.c b/collections/map/map.c index 21af21c..803b5ad 100644 --- a/collections/map/map.c +++ b/collections/map/map.c @@ -1,7 +1,9 @@ #include "map.h" #include <string.h> +#include <stdlib.h> #include <stdio.h> +#include <assert.h> struct map_node { void *key, *val; @@ -9,3 +11,17 @@ struct map_node { struct map_node *left, *right, *parent; }; + +map* map_new(cmp) +cmp_func cmp; +{ + map *tmp; + + tmp = malloc(sizeof(map)); + assert(tmp); + + tmp->cmp = cmp; + tmp->key = tmp->val = tmp->left = tmp->right = tmp->parent = NULL; + + return tmp; +} diff --git a/collections/map/map.h b/collections/map/map.h index a760b45..8aad2f4 100644 --- a/collections/map/map.h +++ b/collections/map/map.h @@ -4,4 +4,7 @@ typedef struct map_node map; typedef int (*cmp_func)(void*, void*); +/*constructors*/ +map* map_new(cmp_func); + #endif |