简单查找结构的键

时间:2014-01-15 02:40:32

标签: 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种类型的食物对象/结构,但搜索的可能性无限。理想情况下,我的结构中不需要char name [20],它将通过变量名称,但我不认为C可以做到这一点。我觉得通过使用多维数组并使用for循环进行搜索可能会更容易。

2 个答案:

答案 0 :(得分:1)

像这样制作一个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
}

答案 1 :(得分:1)

与Fiddling Bits的答案相同,但编码较少

//define constant lookup table
const struct Food foodTable[] = {
    APPLE, CARROT, CANDY,
};
const int foodTable_len = sizeof(foodTable)/sizeof(Food);

Food LookupFunc(const char *foodStr) {
    for (int i=0; i<foodTable_len; i++) {
        bool strMatch = 0 == strcmp(foodTable[i].name, foodStr);
        if (strMatch)
            return foodTable[i];
    }

    //no match. Return something invalid
    return ?;
}

此外,要实现高效,大型的只读映射,可以创建哈希表并使用完美(无冲突)哈希函数。请参阅wikipedia page

上的外部链接部分