//В C нет словаря: это небольшая хеш-таблица
//со строковыми ключами и значениями int
constexpr int BUCKETS = 16;
typedef struct Entry {
char *key;
int value;
struct Entry *next;
} Entry;
typedef struct {
Entry *buckets[BUCKETS];
size_t count;
} Dict;
unsigned dictHash(const char *key) {
unsigned hash = 5381;
for (; *key != '\0'; key++) {
hash = hash * 33 + (unsigned char)*key;
}
return hash % BUCKETS;
}
//указатель на значение или nullptr, если такого ключа нет
int *dictGet(Dict *d, const char *key) {
Entry *e = d->buckets[dictHash(key)];
while (e != nullptr && strcmp(e->key, key) != 0) {
e = e->next;
}
return e != nullptr ? &e->value : nullptr;
}
//добавляет пару или заменяет значение ключа
void dictPut(Dict *d, const char *key, int value) {
int *old = dictGet(d, key);
if (old != nullptr) {
*old = value;
return;
}
unsigned bucket = dictHash(key);
Entry *e = malloc(sizeof *e);
*e = (Entry){strdup(key), value, d->buckets[bucket]};
d->buckets[bucket] = e;
d->count++;
}
//печатает пары в порядке корзин
void dictPrint(const char *name, const Dict *d) {
printf("%s is {", name);
const char *separator = "";
for (int i = 0; i < BUCKETS; i++) {
for (Entry *e = d->buckets[i]; e != nullptr; e = e->next) {
printf("%s\"%s\": %d", separator, e->key, e->value);
separator = ", ";
}
}
printf("}\n");
}
//освобождает каждую пару и оставляет словарь пустым
void dictFree(Dict *d) {
for (int i = 0; i < BUCKETS; i++) {
for (Entry *e = d->buckets[i], *next; e != nullptr; e = next) {
next = e->next;
free(e->key);
free(e);
}
}
*d = (Dict){};
}
//пустой словарь: {} записывает nullptr в каждую корзину
Dict d1 = {};
//d1 is {}
//инициализация данными: таблица пар попадает в словарь
struct { const char *key; int value; } pairs[] = {
{"one", 1}, {"two", 2}, {"three", 3}
};
Dict d2 = {};
for (size_t i = 0; i < sizeof pairs / sizeof pairs[0]; i++) {
dictPut(&d2, pairs[i].key, pairs[i].value);
}
//d2 is {"one": 1, "three": 3, "two": 2}
//порядок - это порядок корзин, а не добавления
dictPrint("d1", &d1);
dictPrint("d2", &d2);
dictFree(&d2);