diff options
Diffstat (limited to 'examples/advanced.c')
| -rw-r--r-- | examples/advanced.c | 31 |
1 files changed, 15 insertions, 16 deletions
diff --git a/examples/advanced.c b/examples/advanced.c index 29ba55aa..aa82e38e 100644 --- a/examples/advanced.c +++ b/examples/advanced.c @@ -8,12 +8,25 @@ * calculate hash values for the individual members, and then somehow combine them into one * hash value for the entire object. * In order to use Viking as a map key, it is smart to define a plain-old-data "view" - * of the Viking struct first. + * of the Viking struct, to simplfy insert and lookup in the map. */ #include <stdio.h> #include <stc/cmap.h> #include <stc/cstr.h> +// Viking data struct ----------------------- + +typedef struct Viking { + cstr_t name; + cstr_t country; +} Viking; + + +void viking_destroy(Viking* vk) { + cstr_destroy(&vk->name); + cstr_destroy(&vk->country); +} + // Viking view struct ----------------------- typedef struct VikingVw { @@ -30,19 +43,6 @@ int vikingvw_equals(const VikingVw* x, const VikingVw* y) { return strcmp(x->country, y->country) == 0; } -// Viking data struct ----------------------- - -typedef struct Viking { - cstr_t name; - cstr_t country; -} Viking; - - -void viking_destroy(Viking* vk) { - cstr_destroy(&vk->name); - cstr_destroy(&vk->country); -} - VikingVw viking_toVw(Viking* vk) { VikingVw vw = {vk->name.str, vk->country.str}; return vw; } @@ -50,7 +50,6 @@ Viking viking_fromVw(VikingVw vw) { Viking vk = {cstr_make(vw.name), cstr_make(vw.country)}; return vk; } - // Using the full declare_cmap() macro to define [Viking -> int] hash map type: declare_cmap(vk, Viking, int, c_default_destroy, vikingvw_equals, vikingvw_hash, viking_destroy, VikingVw, viking_toVw, viking_fromVw); @@ -72,7 +71,7 @@ int main() VikingVw einar = {"Einar", "Norway"}; cmap_vk_entry_t *e = cmap_vk_find(&vikings, einar); e->value += 5; // update - cmap_vk_emplace(&vikings, einar, 0).item->value += 5; // again + cmap_vk_insert(&vikings, einar, 0).item->value += 5; // again c_foreach (k, cmap_vk, vikings) { printf("%s of %s has %d hp\n", k.item->key.name.str, k.item->key.country.str, k.item->value); |
