【发布时间】:2014-02-03 08:59:33
【问题描述】:
有没有办法在这段代码中实现“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 APPLE...而不是struct Opcode APPLE...吗? -
是的,抱歉我现在修好了
-
您的直觉是正确的 - C 在运行时不会保留任何变量或字段名称,因此您需要注意将值存储在数据结构中,以便之后进行搜索。我要补充的唯一建议是,您可能需要考虑对变量名称/类别使用枚举而不是字符串。
标签: c hashmap hashtable associative-array