arrays - 如何将枚举与字符串数组相关联
问题描述
如果我有课程名称的数组字符串,例如
courseName = {"java","math","physics"}
并enum
为课程提供带有代码的常量变量,例如
CSC = 320
如何在 C 语言中关联它们?
解决方案
您需要某种方法将枚举映射到数组索引。
一个带有“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;
}
请注意,这只是一种可能的解决方案。这很简单,但不是很有效。
推荐阅读
- php - Laravel syncWithoutDetaching 额外字段
- c - CS50 pset4 滤镜“模糊
- angular - 未知错误:错误:没有为 src\main\ui\node_modules\uuid 找到有效的导出 main?
- php - FreeTDS + Doctrine 去除零小数
- express - 即使我调用 server.close(),Mocha 也不会退出
- html - 缺少有效的 YouTube API 密钥
- xml - 使用单个 XSLT 生成不同的输出文件
- sql - 查找表中每个实体的最大 N 值的最有效 SQL 查询是什么
- laravel - 在 Laravel 中执行 CRUD 的单个函数
- php - php file_put_content 到 aws S3