typedef enum input
typedef enum input
如果我们在 C++ 中有这个:
typedef enum {Unknown,USA,Canada,France,England,Italy,Spain,Australia,} origin_t;
origin_t Country;
char *current;
cin>>current;
我们如何Country
设置为用户输入的 c 字符串current
?除了一个接一个比较,因为我们有一个很大的列表?最快的方法?谢谢。
enum
和string
之间没有直接的转换,也没有像Java那样在C++中char*
。
一个有效的方法是拥有一张地图:
#include <map>
#include <string>
typedef enum {Unknown,USA,Canada,France,England,Italy,Spain,Australia,} origin_t;
std::map<std::string, origin_t> countries;
countries["Unknown"] = Unknown;
countries["USA"] = USA;
//...
origin_t Country;
std::string current;
cin>>current;
Country = countries[current];
请注意,在我的示例中,我使用的是std::string
而不是char*
,除非您有充分的理由使用char*
,否则您应该这样做。
我使用的是一个 POD 结构数组。 该结构包含一个枚举和一个与特定枚举对应的字符的常量字符 *。 然后我使用 std::find 查找枚举或字符 * 根据需要查找枚举或字符 *。
POD 数组的优点是所有内容都在程序加载时初始化。 无需加载地图。
缺点是 std::find 的线性搜索。 但这从来都不是问题,因为我从来没有大量的枚举值。
以上内容都隐藏在实现文件中。 标头只有函数。 通常一个从枚举转换为 std::string,另一个从 std::string 转换为枚举。
相关文章:
- enum是C++中的宏变量还是整数变量
- 是否可以从int转换为enum类类型
- 在一个模板函数中,若输入的类型是enum类,我该如何使用std::underlying_type
- "input.length();"的目的是什么?
- 在C++中,将int值赋给enum,反之亦然
- 两个 COM 组件中 ENUM 的重复条目
- 如何使用"derived input class"创建派生类?
- 类继承,ENUM 与 AST 类实现的问题
- C++关于ENUM的问题。我得到的响应比枚举列表大
- 开放CV垫"Sizes of input arguments do not match"的问题
- sizeof(enum) 可以不同于 sizeof(std::underlying_type<Enum>::
- 如何理解c++中在命名空间内部定义的枚举类型enum
- 如何将set和enum一起使用
- 如何限制从int到enum类的转换
- 编译为 cuda 内核调用提供了"expression must have integral or unscoped enum type"
- 什么是"Reading unbounded stream from standard input (Memory Management)"的例子
- 如何检查输入是否为字符并显示它是"invalid input",否则它将按原样运行
- 输出 [left]=input[i] 行中的 c++ 代码中存在无效的类型错误
- Access C++ Enum from Swift
- typedef enum input