From 50846316de122801e07511d4e3771a4561efa5ad Mon Sep 17 00:00:00 2001 From: Tucker Evans Date: Mon, 6 Jul 2020 15:49:49 -0400 Subject: Add size function for maps --- collections/map/map.adoc | 21 ++++++++++++++++++++- collections/map/map.c | 9 +++++++++ collections/map/map.h | 3 +++ 3 files changed, 32 insertions(+), 1 deletion(-) diff --git a/collections/map/map.adoc b/collections/map/map.adoc index fc6b8b7..837a08a 100644 --- a/collections/map/map.adoc +++ b/collections/map/map.adoc @@ -1,7 +1,7 @@ Map === Tucker Evans -v0.1, 2020-07-06 +v0.2, 2020-07-06 A basic map implemented in an AVL tree. @@ -50,3 +50,22 @@ Examples map *dict = map_new((cmp_func) strcmp); ---- + +[[map_size]] ++map_size(map *self)+ +~~~~~~~~~~~~~~~~~~~~~ +Returns the number of key, value pairs stored in map +self+. + +Examples +^^^^^^^^ +[source,c] +---- +#include "map.h" +#include + +map *dict = map_new((cmp_func) strcmp); + +assert(map_size(dict) == 0); +map_set(dict, "ONE", NULL); +assert(map_size(dict) == 1); +---- diff --git a/collections/map/map.c b/collections/map/map.c index 803b5ad..712a895 100644 --- a/collections/map/map.c +++ b/collections/map/map.c @@ -25,3 +25,12 @@ cmp_func cmp; return tmp; } + +int map_size(root) +map *root; +{ + if (!root || !root->key) + return 0; + + return map_size(root->left) + map_size(root->right) + 1; +} diff --git a/collections/map/map.h b/collections/map/map.h index 8aad2f4..ef4b0c8 100644 --- a/collections/map/map.h +++ b/collections/map/map.h @@ -7,4 +7,7 @@ typedef int (*cmp_func)(void*, void*); /*constructors*/ map* map_new(cmp_func); +/*management*/ +int map_size(map*); + #endif -- cgit v1.1