在用C语言编写程序时,我错过了一件事,那就是字典数据 struct .用C语言实现的最方便的方式是什么?我不是在寻找性能,而是从头开始编码的简便性.我也不希望它是通用的--大约char*int就可以了.但我确实希望它能够存储任意数量的物品.

这更像是一种练习.我知道有第三方图书馆可以使用.但是考虑一下,它们不存在.在这种情况下,实现满足上述要求的词典的最快方法是什么.

推荐答案

Section 6.6 of The C Programming Language presents a simple dictionary (hashtable) data structure. I don't think a useful dictionary implementation could get any simpler than this. For your convenience, I reproduce the code here.

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来降低碰撞的可能性.有关数据 struct 的完整讨论,请参阅本书.

C++相关问答推荐

VS代码输入需要多次

带双指针的2D数组

你能用自己的地址声明一个C指针吗?

为什么getchar()挂起了,尽管poll()返回了一个好的值?""

当main函数调用被重构时,C函数给出错误的结果

在C中将通用字符名称转换为UTF-8

文件权限为0666,但即使以超级用户身份也无法打开

试图从CSV文件中获取双精度值,但在C++中始终为空

使用错误的命令执行程序

有什么方法可以将字符串与我们 Select 的子字符串分开吗?喜欢:SIN(LOG(10))

如何使用_newindex数组我总是得到错误的参数

将返回的char*设置为S在函数中定义的字符串文字可能会产生什么问题?

C11/C17标准允许编译器清除复合文字内存吗?

安全倒计时循环

合并对 struct 数组进行排序

可以对两种 struct 类型中的任何一种进行操作的C函数

%g浮点表示的最大字符串长度是多少?

无法将字符串文字分配给 C 中的字符数组

无法理解 fgets 输出

全局变量 y0 与 mathlib 冲突,无法编译最小的 C 代码