c - 结构体键的简单查找

标签 c hashmap hashtable associative-array

有没有办法在这段代码中实现“LookupFunc”:

enum FoodType { FRUIT, VEGGIE, DESSERT };

struct Food {
    char name[20];
    int index;
    FoodType type;
};

struct Food APPLE = {"apple", 0, FRUIT};
struct Food CARROT = {"carrot", 1, VEGGIE};
struct Food CANDY = {"candy", 2, DESSERT};


struct Food f = LookupFunc("apple");
printf("indexof apple: %d\n", f.index);
printf("type of apple: %d\n", f.type);

我只有 8 种类型的 Food 对象/结构,但搜索的可能性是无限的。理想情况下,我的结构中不需要 char name[20],它会通过变量名称,但我不认为 C 可以做到这一点。我有一种感觉,通过使用多维数组并使用 for 循环进行搜索可能会更容易。

最佳答案

创建一个 struct Food 数组,如下所示:

#define MAX_FOODS (8)
struct Food foods[MAX_FOODS] = {
                                   {"apple", 0, FRUIT},
                                   {"carrot", 1, VEGGIE},
                                   {"candy", 2, DESSERT},
                                   ...
                               };

这样,搜索和索引就会变得很容易。

int i = LookupFunc("apple");

int LookupFunc(char *str)
{
    for(int i = 0; i < MAX_FOODS; i++)
    {
        if(strcmp(foods[i].name, str) == 0)
            return i;
    }

    return -1; // Not found
}

关于c - 结构体键的简单查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21128150/

相关文章:

c++ - 插入排序错误

javascript - 将对象转换为对象字典

parsing - powershell 和字符串从非结构化文本到 hashtab

c - 将 GHashTable 转储到文件

iphone - objective-c 中局部常量的最佳实践

编译 glibc :/glibc-2. 7/w/elf/ld.so: 没有那个文件或目录

c - fgetc 无法加载文件的最后一个字符

java - 如何更新 HashMap 中键的值?

java - 是否可以将文件保存到任何集合(例如 HashMap 或哈希表)中?

python - 如何预先确定为 N 个项目创建哈希表的理想大小?