有没有办法在这段代码中实现“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/