Files
hm.h/main.c
2025-11-18 21:33:06 +01:00

59 lines
1.5 KiB
C

#include <stdio.h>
#define HM_IMPLEMENTATION
#define HM_INITIAL_CAPACITY 1
#include "hm.h"
void print_hm(const HashMap *hm)
{
HashMapIterator it = hm_iterate(hm);
while (hm_next(&it) != NULL) {
printf("%-15s: ", (const char*)hm_key(&it));
printf("%d\n", *(int*)hm_value(&it));
}
}
const char *words[49] = {
"apple", "banana", "cherry", "date", "elderberry", "fig", "grape",
"honeydew", "apple", "banana", "kiwi", "lemon", "mango", "nectarine",
"orange", "papaya", "quince", "raspberry", "strawberry", "tangerine",
"ugli", "voavanga", "watermelon", "xigua", "yellowfruit", "zucchini",
"apple", "banana", "cherry", "mango", "kiwi", "lemon", "lemon", "orange",
"papaya", "papaya", "grape", "grape", "grape", "strawberry", "strawberry",
"date", "date", "date", "fig", "fig", "elderberry", "nectarine", "plum"
};
const size_t N = sizeof(words)/sizeof(words[0]);
const int ONE = 1;
int main(void)
{
HashMap freq = hm_create(0, sizeof(int));
for (size_t i = 0; i < N; ++i) {
const char *word = words[i];
int *f = hm_get(&freq, word);
if (f == NULL) {
hm_put(&freq, word, &ONE);
} else {
*f += 1;
}
}
print(&freq);
printf("count = %zu\n", freq.count);
HashMapIterator it = hm_iterate(&freq);
hm_next(&it);
while (hm_value(&it) != NULL) {
const void *key = hm_key(&it);
hm_next(&it);
hm_remove(&freq, key);
}
printf("count = %zu\n", freq.count);
hm_free(&freq);
return 0;
}