在使用C语言编写程序时,我错过的一件事情就是字典数据结构。在C语言中,最方便实现字典数据结构的方法是什么?我不是寻求高性能的实现方式,而是希望从零开始轻松编码实现它。我也不希望它具有通用性 - 一个类似于 char*
→int
的东西就可以了。但我确实希望它能够存储任意数量的项目。
这只是一种练习。我知道有第三方库可用,但考虑一下,如果它们不存在,你可以以最快的方式实现满足上述要求的字典吗?
在使用C语言编写程序时,我错过的一件事情就是字典数据结构。在C语言中,最方便实现字典数据结构的方法是什么?我不是寻求高性能的实现方式,而是希望从零开始轻松编码实现它。我也不希望它具有通用性 - 一个类似于 char*
→int
的东西就可以了。但我确实希望它能够存储任意数量的项目。
这只是一种练习。我知道有第三方库可用,但考虑一下,如果它们不存在,你可以以最快的方式实现满足上述要求的字典吗?
《C程序设计语言》第6.6节介绍了一种简单的字典(哈希表)数据结构。我认为没有比这更简单且有用的字典实现了。为了方便起见,我在此处重复代码。
struct nlist { /* table entry: */
struct nlist *next; /* next entry in chain */
char *name; /* defined name */
char *defn; /* replacement text */
};
#define HASHSIZE 101
static struct nlist *hashtab[HASHSIZE]; /* pointer table */
/* hash: form hash value for string s */
unsigned hash(char *s)
{
unsigned hashval;
for (hashval = 0; *s != '\0'; s++)
hashval = *s + 31 * hashval;
return hashval % HASHSIZE;
}
/* lookup: look for s in hashtab */
struct nlist *lookup(char *s)
{
struct nlist *np;
for (np = hashtab[hash(s)]; np != NULL; np = np->next)
if (strcmp(s, np->name) == 0)
return np; /* found */
return NULL; /* not found */
}
char *strdup(char *);
/* install: put (name, defn) in hashtab */
struct nlist *install(char *name, char *defn)
{
struct nlist *np;
unsigned hashval;
if ((np = lookup(name)) == NULL) { /* not found */
np = (struct nlist *) malloc(sizeof(*np));
if (np == NULL || (np->name = strdup(name)) == NULL)
return NULL;
hashval = hash(name);
np->next = hashtab[hashval];
hashtab[hashval] = np;
} else /* already there */
free((void *) np->defn); /*free previous defn */
if ((np->defn = strdup(defn)) == NULL)
return NULL;
return np;
}
char *strdup(char *s) /* make a duplicate of s */
{
char *p;
p = (char *) malloc(strlen(s)+1); /* +1 for ’\0’ */
if (p != NULL)
strcpy(p, s);
return p;
}
请注意,如果两个字符串的哈希值发生冲突,可能会导致 O(n)
的查找时间。您可以通过增加 HASHSIZE
的值来减少碰撞的可能性。有关该数据结构的完整讨论,请参阅书籍。
hashval = *s + 31 * hashval;
中的常数值是31而不是其他任何值? - Incerteza最快的方法是使用已经存在的实现,比如uthash。
如果你真的想要自己编码,可以检查和重用uthash
的算法。它采用BSD许可证,因此除了需要传达版权声明之外,你在使用上几乎没有限制。
为了方便实现,最简单的方法是通过对数组进行朴素搜索。除了一些错误检查外,这就是一个完整的实现(未经测试)。
typedef struct dict_entry_s {
const char *key;
int value;
} dict_entry_s;
typedef struct dict_s {
int len;
int cap;
dict_entry_s *entry;
} dict_s, *dict_t;
int dict_find_index(dict_t dict, const char *key) {
for (int i = 0; i < dict->len; i++) {
if (!strcmp(dict->entry[i], key)) {
return i;
}
}
return -1;
}
int dict_find(dict_t dict, const char *key, int def) {
int idx = dict_find_index(dict, key);
return idx == -1 ? def : dict->entry[idx].value;
}
void dict_add(dict_t dict, const char *key, int value) {
int idx = dict_find_index(dict, key);
if (idx != -1) {
dict->entry[idx].value = value;
return;
}
if (dict->len == dict->cap) {
dict->cap *= 2;
dict->entry = realloc(dict->entry, dict->cap * sizeof(dict_entry_s));
}
dict->entry[dict->len].key = strdup(key);
dict->entry[dict->len].value = value;
dict->len++;
}
dict_t dict_new(void) {
dict_s proto = {0, 10, malloc(10 * sizeof(dict_entry_s))};
dict_t d = malloc(sizeof(dict_s));
*d = proto;
return d;
}
void dict_free(dict_t dict) {
for (int i = 0; i < dict->len; i++) {
free(dict->entry[i].key);
}
free(dict->entry);
free(dict);
}
我很惊讶没有人提到 hsearch/hcreate 库集,虽然它在Windows上不可用,但是它被POSIX所规定,因此在Linux/GNU系统中可以使用。
该链接有一个简单而完整的基本示例,非常好地解释了它的用法。
它甚至具有线程安全变体,易于使用且性能非常好。
GLib: GNOME项目的https://developer.gnome.org/glib/。在https://developer.gnome.org/glib/stable/glib-data-types.html文档中记录了几个容器,包括"哈希表"和"平衡二叉树"。许可证:LGPL。
gnulib: GNU项目的https://www.gnu.org/software/gnulib/。您应该将源代码复制粘贴到您的代码中。在https://www.gnu.org/software/gnulib/MODULES.html#ansic_ext_container文档中记录了几个容器,包括"rbtree-list"、"linkedhash-list"和"rbtreehash-list"。GPL许可证。
这里是一个快速的实现,我用它从字符串中获取了一个'Matrix'(结构体)。你也可以有一个更大的数组,并在运行时更改其值:
typedef struct { int** lines; int isDefined; }mat;
mat matA, matB, matC, matD, matE, matF;
/* an auxilary struct to be used in a dictionary */
typedef struct { char* str; mat *matrix; }stringToMat;
/* creating a 'dictionary' for a mat name to its mat. lower case only! */
stringToMat matCases [] =
{
{ "mat_a", &matA },
{ "mat_b", &matB },
{ "mat_c", &matC },
{ "mat_d", &matD },
{ "mat_e", &matE },
{ "mat_f", &matF },
};
mat* getMat(char * str)
{
stringToMat* pCase;
mat * selected = NULL;
if (str != NULL)
{
/* runing on the dictionary to get the mat selected */
for(pCase = matCases; pCase != matCases + sizeof(matCases) / sizeof(matCases[0]); pCase++ )
{
if(!strcmp( pCase->str, str))
selected = (pCase->matrix);
}
if (selected == NULL)
printf("%s is not a valid matrix name\n", str);
}
else
printf("expected matrix name, got NULL\n");
return selected;
}
哈希是关键。我认为可以使用查找表和哈希密钥来实现。你可以在网上找到许多哈希函数。
Redis 是一个很好的参考,因为它是一个键值系统,它的哈希表是一个很好的例子。