C ++-从字符串变量获取枚举值 [英] C++ - Getting an enumerated value from a string variable
问题描述
我有一个枚举类型,例如
枚举颜色(红色,蓝色,绿色);
和一个CString test_string ="Blue"
如何通过字符串获取枚举类型的第二个值?
我想去的是:
int retValue =颜色(test_string);
或类似的东西将产生retValue = 1
我不想使用if语句或case语句来完成此操作,因为枚举中大约有100个元素.我还想使它尽可能简单(我不是一个出色的C程序员).
I have an enumerated type such as
enum Colors(Red, Blue, Green);
and a CString test_string = "Blue"
How do I get to the 2nd value in the enumerated type by the string?
What I am trying to get to is:
int retValue = Colors(test_string);
or something like that that will produce retValue = 1
I do not want to use if statements or case statements to accomplish this since I have about 100 elements in the enumeration. I would also like to keep this a simple as possible (I am not a great C programmer).
推荐答案
使用C++
,您必须做一些工作(C#
,例如轻轻地提供它.)
您最好的选择是(不幸的是,也许...)std::map
.
WithC++
you have to do some work (C#
, for instance gently provides it).
Your best bet is (unfortunately, maybe...) astd::map
.
// the enum
enum Color
{
Red,
Green,
Blue
};
// the mapping of the string with the enum
map<CString , Color> m;
m.insert(make_pair<CString, Color>(_T("Red"),Red));
m.insert(make_pair<CString, Color>(_T("Green"),Green));
m.insert(make_pair<CString, Color>(_T("Blue"),Blue));
// usage...
Color c = m[_T("Green")];
无法像您想要的那样在运行时通过字符串访问枚举值.
将所有可能的小数点放在与您的枚举相对应的数组中,并使用循环遍历数组以查找字符串的int值.
There is no way to access the enum value by a string at runtime, like you want.
Put all possible srings in an array corresponding to your enumeration and use a loop to iterate through the array to find the int value for your string.
这种用法也可以考虑:
This usage could be thinkable too:
Colored<CString, Blue> cszString(_T("Blue"));
ASSERT(Blue == cszString.GetColor());
我会在您需要时描述它...:)
I describe it when you will want it... :)
这篇关于C ++-从字符串变量获取枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!