C - 如何将多个值分配给 HashMap 中的同一个键?

标签 c algorithm pointers data-structures linked-list

作为一名新手程序员,我开始通读 The C Programming Language了解有关指针结构 的更多信息。

我目前正在学习 C 中的 hashmap。按照书中的示例,我创建了自己的 hashmap 来保存键值对:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_STRING_SIZE 100
#define HASHSIZE 101

static struct map *hashtab[HASHSIZE]; /* pointer table */
unsigned hash(char *);  /* hashing function: form hash value for string s. used by both lookup and install*/
char *strdup(char *);

struct map {        /* creating a map structure */
    struct map *next;
    char *KEY;          /* KEY - pointer to a char - member of nlist*/
    char *object1;      /* object - pointer to a char - member of nlist*/
};

/* lookup function takes a pointer to char - s as an argument and returns a pointer to map structure */
struct map *lookup(char *s) {
    struct map *np;

    for (np = hashtab[hash(s)]; np != NULL; np = np->next) {
        if (strcmp(s, np->KEY) == 0) {
            return np;
        }
    }
    return NULL;
}

/* install function takes a pointer to a char - KEY, object and returns a pointer to map structure */
struct map *install(char *KEY, char *object1) {
    /* install: put (name, defn) in */
    /* Install uses lookup to determine whether the KEY being installed
       is already present. Proceeds to create a new entry or update*/
    struct map *np;
    unsigned hashval;

    if ((np = lookup(KEY)) == NULL) {
        np = (struct map *) malloc(sizeof(*np));
        if (np == NULL || (np->KEY = strdup(KEY)) == NULL) {
            return NULL;
        }
        hashval = hash(KEY);
        np->next = hashtab[hashval];
        hashtab[hashval] = np;
    }
    else {
        free((void *)np->object1);
    }
    if ((np->object1 = strdup(object1)) == NULL) {
        return NULL;
    }
    return np;
}

然后我按如下方式为键分配值:

int main(void) {

    struct map *table[4] = {
        (install("key1", "value1")),
        (install("key2", "value2")),
        (install("key3", "value3")),
        (install("key4", "value4"))
    };

    int i;

    for (i = 0; i < 4; i++) {
        printf("%s->%s\n", table[i]->KEY, table[i]->object);
    }
    printf("\n");
    return 0;
}

上面的代码运行良好,我可以将 value1, ... , value4 分配给 key1, ... ,key4 分别。但是,这不允许我为同一个键分配多个值。

假设我从文本文件中读取了以下内容:

key1 9000 600 Test1
key2 2000 600 Test2
key3 3000 120 Test3
key4 4000 120 Test4
.
.
key10 1000 560 Test10

我希望能够存储每个键并为其分配多个值。由于列数是固定的,也许我可以有一个表示一行的结构并将其放入 map 中。

为此,需要修改 install 以便能够为同一键添加多个值。由于 key 是唯一的,lookupuninstall(我创建的用于删除 key 的函数)应该保持不变。

上面的代码工作得很好,但是我正在寻找一个通用的解决方案来为同一个键添加多个值。

我应该如何继续才能调用:

struct map *table[4] = {
    (install("key1", "9000" ,"600", "Test1")),   //key, object1, object2, object3
    (install("key2", "2000" ,"600", "Test2")),
    (install("key3", "3000" ,"120", "Test3")),
    (install("key4", "4000" ,"120", "Test4"))
};

另一个想法是:

/* key points to this struct */
struct Value {
    int i;
    int k;
    char *c;
};

typedef struct map {        /* creating a map structure */
    struct map *next;
    char *KEY;
    struct Value value;  /* place multiple values inside a struct*/
};

这就是我卡住的地方:

struct map *insert(char *KEY, struct *Value) {
    struct map *np;
    unsigned hashval;

    if ((np = lookup(KEY)) == NULL) {
        np = (struct map *) malloc(sizeof(*np));
        if (np == NULL || (np->KEY = strdup(KEY)) == NULL) {
            return NULL;
        }
        hashval = hash(KEY);
        np->next = hashtab[hashval];
        hashtab[hashval] = np;
    }
    else {
        free((struct Value*)np->value); //type cast cannot convert from 'Value' to 'Value*'

    }
    if ((np->Value = strdup(Value)) == NULL) { //map has no field value
        return NULL;
    }

    return np;
}

我搜索了以下问题,但是无法提取有关如何在 C 中实现它的相关信息。

Hashmaps having multiple keys with multiple values

How can I assign multiple values to a hash key?

HashMap with multiple valued keys

我如何实现一个 hashmap,它接受分配给同一个键的多个值?


编辑

正如评论中所指出的,我使用的结构实际上可能不是 HashMap ,而是链表。然而 book具体说第 144 页是一个 HashMap 。

最佳答案

这可能不是最好的解决方案,但由于上述评论,我得到了一些工作。我将多个值声明为指向 char 的指针。如果我可以改进这一点,请告诉我。

我还没有实现碰撞校正。

struct map {        /* creating a map structure */
    struct map *next;
    char *KEY;
    char *value1;
    char *value2;
    char *value3;
}; 

然后我将这些传递给插入函数。

struct map *insert(char *KEY, char *value1, char *value2, char *value3) {
    /* install: put (name, defn) in */
    /* Install uses lookup to determine whether the KEY being installed
       is already present. Proceeds to create a new entry or update*/
    struct map *np;
    unsigned hashval;

    if ((np = lookup(KEY)) == NULL) {
        np = (struct map *) malloc(sizeof(*np));
        if (np == NULL || (np->KEY = strdup(KEY)) == NULL) {
            return NULL;
        }
        hashval = hash(KEY);
        np->next = hashtab[hashval];
        hashtab[hashval] = np;
    }
    else {
        free((void *)np->value1); //type cast cannot convert from 'Value' to 'Value*'
        free((void *)np->value2);
        free((void *)np->value3);
    }
    if ((np->time = strdup(value1)) == NULL) { //map has no field value
        return NULL;
    }
    if ((np->description = strdup(value2)) == NULL) { //map has no field value
        return NULL;
    }
    if ((np->duration = strdup(value3)) == NULL) { //map has no field value
        return NULL;
    }

    return np;
}

打印这些将给出指向四个值的键。

key1->value1 value2 value3

关于C - 如何将多个值分配给 HashMap 中的同一个键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53248647/

相关文章:

C 指针减法

c - 仅使用 SSE2 提取 SSE 洗牌后的 32 位值

c++ - 使用 OpenGL 渲染 VAAPI 表面?

python - 下一个更高的素数和回文数

Java - 使用哈希函数进行递归字符串解析

c++ - std::list::sort 和指向元素的指针

c++ - 一种保护通过网络发送的数据的方法?

c - PIC/PIE 二进制文件中全局符号表 (GOT) 的地址

algorithm - 排序数据结构 : random in, 最低出

json - 将 time.Date 分配给 *time.Time 指针以测试 JSON 反序列化