From f76354cd0864b2791911b48c16f26f20b667081a Mon Sep 17 00:00:00 2001 From: Tyge Løvset <60263450+tylov@users.noreply.github.com> Date: Mon, 4 Jan 2021 09:27:48 +0100 Subject: Update cmap_api.md --- docs/cmap_api.md | 73 +++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 72 insertions(+), 1 deletion(-) diff --git a/docs/cmap_api.md b/docs/cmap_api.md index 0ef6441f..cad0887a 100644 --- a/docs/cmap_api.md +++ b/docs/cmap_api.md @@ -167,7 +167,7 @@ The HEX of color BLACK is:[#000000] ``` ### Example 2 -This example uses a cmap with cstr_t as mapped value, by the `using_cmap_strval(id, int)` macro. +This example uses a cmap with cstr as mapped value, by the `using_cmap_strval(id, int)` macro. ```c #include "stc/cstr.h" #include "stc/cmap.h" @@ -203,3 +203,74 @@ Output: 110: White 120: #cc7744ff ``` + +### Example 3 +Demonstrate cmap with plain-old-data struct key type Vec3f: cmap: +```c +#include "stc/cmap.h" +#include + +typedef struct { float x, y, z; } Vec3f; + +using_cmap(v3, Vec3f, int, c_default_del, + c_default_clone, + c_mem_equals, + c_default_hash32); + +int main() +{ + cmap_v3 vecs = cmap_v3_init(); + + cmap_v3_put(&vecs, (Vec3f){1.0f, 0.0f, 0.0f}, 1); + cmap_v3_put(&vecs, (Vec3f){0.0f, 1.0f, 0.0f}, 2); + cmap_v3_put(&vecs, (Vec3f){0.0f, 0.0f, 1.0f}, 3); + cmap_v3_put(&vecs, (Vec3f){1.0f, 1.0f, 1.0f}, 4); + + c_foreach (i, cmap_v3, vecs) + printf("{%f %f %f}: %d\n", i.ref->first.x, i.ref->first.y, i.ref->first.z, i.ref->second); + puts(""); + + cmap_v3_del(&vecs); +} +``` +Output: +```c +{1.000000 1.000000 1.000000}: 4 +{1.000000 0.000000 0.000000}: 1 +{0.000000 1.000000 0.000000}: 2 +{0.000000 0.000000 1.000000}: 3 +``` + +### Example 4 +Inverse: demonstrate cmap with mapped POD type Vec3f: cmap: +```c +#include "stc/cmap.h" +#include + +typedef struct { float x, y, z; } Vec3f; + +using_cmap(iv, int, Vec3f); + +int main() +{ + cmap_iv vecs = cmap_iv_init(); + + cmap_iv_put(&vecs, 1, (Vec3f){1.0f, 0.0f, 0.0f}); + cmap_iv_put(&vecs, 2, (Vec3f){0.0f, 1.0f, 0.0f}); + cmap_iv_put(&vecs, 3, (Vec3f){0.0f, 0.0f, 1.0f}); + cmap_iv_put(&vecs, 4, (Vec3f){1.0f, 1.0f, 1.0f}); + + c_foreach (i, cmap_iv, vecs) + printf("%d: {%f %f %f}\n", i.ref->first, i.ref->second.x, i.ref->second.y, i.ref->second.z); + puts(""); + + cmap_iv_del(&vecs); +} +``` +Output: +```c +4: {1.000000 1.000000 1.000000} +3: {0.000000 0.000000 1.000000} +2: {0.000000 1.000000 0.000000} +1: {1.000000 0.000000 0.000000} +`````` -- cgit v1.2.3