typedef enum input

typedef enum input

本文关键字:input enum typedef      更新时间:2023-10-16

如果我们在 C++ 中有这个:

typedef enum {Unknown,USA,Canada,France,England,Italy,Spain,Australia,} origin_t;
origin_t Country;
char *current;
cin>>current;

我们如何Country设置为用户输入的 c 字符串current?除了一个接一个比较,因为我们有一个很大的列表?最快的方法?谢谢。

enumstring之间没有直接的转换,也没有像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 转换为枚举。