libcdsb/examples/map.c

60 lines
1.2 KiB
C
Raw Normal View History

2022-08-16 21:11:07 +03:00
/* This software is licensed by the MIT License, see LICENSE file */
/* Copyright © 2022 Gregory Lirent */
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
2022-08-19 18:46:51 +03:00
#include "../include/map.h"
2022-08-16 21:11:07 +03:00
typedef vtype_map map_t;
2023-03-23 18:18:51 +03:00
int print_value(vtype_variable key, vtype_variable value, void* data) {
2022-08-16 21:11:07 +03:00
const char *n = data;
2023-03-23 18:18:51 +03:00
vtype_int32 *k = (void*)key.pointer;
2022-08-16 21:11:07 +03:00
2023-03-23 18:18:51 +03:00
assert(key.type == VTYPE_INT32);
2022-08-16 21:11:07 +03:00
printf("%s %d: ", n, *k);
2023-03-23 18:18:51 +03:00
switch (value.type) {
2022-08-16 21:11:07 +03:00
default: abort();
case VTYPE_INT32:
2023-03-23 18:18:51 +03:00
printf("%d\n", *(vtype_int32*)value.pointer);
2022-08-16 21:11:07 +03:00
break;
case VTYPE_FLOAT:
2023-03-23 18:18:51 +03:00
printf("%f\n", *(vtype_float*)value.pointer);
2022-08-16 21:11:07 +03:00
break;
}
return 0;
}
int main(int argc, char** argv) {
map_t map;
vtype_float fl = 0.0;
2022-08-19 18:46:51 +03:00
int a, b;
2022-08-16 21:11:07 +03:00
map_init(&map, VTYPE_INT32);
2022-08-19 18:46:51 +03:00
for (vtype_int32 i = 0; i < 28; ++i) {
2022-08-16 21:11:07 +03:00
if (i%2) {
2022-08-19 18:46:51 +03:00
map_update(&map, i, i);
2022-08-16 21:11:07 +03:00
} else {
2022-08-19 18:46:51 +03:00
map_update(&map, i, fl);
2022-08-16 21:11:07 +03:00
fl += 0.05;
}
}
2022-08-19 18:46:51 +03:00
a = 13;
b = 18;
map_get(&map, a, "Get value:", print_value);
map_pop(&map, b, "Pop value:", print_value);
2022-08-16 21:11:07 +03:00
map_foreach(&map, "Foreach loop:", print_value);
map_free(&map);
}