Frage

Is there a way to implement the 'LookupFunc' in this code:

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);

I will have only 8 types of Food object/structs, but unlimited possibilities to search. Ideally, char name[20], would not be needed in my struct and it would go by variable name but I don't think C can do that. I have a feeling this may be easier by using multidimensional arrays and searching using a for loop.

War es hilfreich?

Lösung

Make an array of struct Food like this:

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

This way, it'll be easy to search and index.

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
}

Andere Tipps

Same idea as Fiddling Bits's answer, but with less hard coding

//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 ?;
}

Also, to implement an efficient, large, read-only map, one can make a hash table and use a perfect (collision free) hash function. See the external links section on the wikipedia page

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top