首页 > 解决方案 > 如何将枚举与字符串数组相关联

问题描述

如果我有课程名称的数组字符串,例如
courseName = {"java","math","physics"}

enum为课程提供带有代码的常量变量,例如
CSC = 320

如何在 C 语言中关联它们?

标签: arrayscstringenums

解决方案


您需要某种方法将枚举映射到数组索引。

一个带有“from”和“to”成员的简单结构数组解决了这个问题:

struct
{
    int course;     // Course enumeration value
    unsigned name;  // Name array index
} course_to_name_map[] = {
    { JAVA_101, 0 },
    // etc...
};

查找名称循环遍历映射数组找到课程,然后使用对应的索引获取名称:

char *get_course_name(int course)
{
    static const size_t map_element_count = sizeof course_to_name_map / sizeof course_to_name_map[0];

    for (unsigned i = 0; i < map_element_count; ++i)
    {
        if (course_to_name_map[i].course == course)
        {
            return course_names[course_to_name_map[i].name];
        }
    }

    // Course was not found
    return NULL;
}

请注意,这只是一种可能的解决方案。这很简单,但不是很有效。


推荐阅读