//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);