C++ 字符串枚举

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7163069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:33:08  来源:igfitidea点击:

C++ string to enum

c++stringenums

提问by Daniel

Is there a simple way in C++ to convert a string to an enum (similar to Enum.Parsein C#)? A switch statement would be verylong, so I was wondering if there is a simpler way to do this?

C++ 中是否有一种简单的方法可以将字符串转换为枚举(类似于Enum.ParseC#)?switch 语句会长,所以我想知道是否有更简单的方法来做到这一点?

EDIT:

编辑:

Thanks for all of your replies. I realized that there was a much simpler way to do it for my particular case. The strings always contained the charater 'S' followed by some number so i just did

感谢您的所有回复。我意识到对于我的特殊情况,有一种更简单的方法可以做到这一点。字符串总是包含字符 'S' 后跟一些数字,所以我只是做了

int i = atoi(myStr.c_str() + 1);

and then did a switch on i.

然后在 i 上做了一个开关。

回答by Mark Ransom

A std::map<std::string, MyEnum>(or unordered_map) could do it easily. Populating the map would be just as tedious as the switch statement though.

A std::map<std::string, MyEnum>(或unordered_map) 可以轻松完成。不过,填充地图与 switch 语句一样乏味。

Edit: Since C++11, populating is trivial:

编辑:从 C++11 开始,填充是微不足道的:

static std::unordered_map<std::string,E> const table = { {"a",E::a}, {"b",E::b} };
auto it = table.find(str);
if (it != table.end()) {
  return it->second;
} else { error() }

回答by Nawaz

Use std::map<std::string, Enum>and use boost::map_list_ofto easilyinitialize it.

使用std::map<std::string, Enum>和使用boost::map_list_of,以轻松初始化。

Example,

例子,

enum X
{
   A,
   B,
   C
};

std::map<std::string, X> xmap = boost::map_list_of("A", A)("B", B)("C",C);

回答by Guy L

saw this example somewhere

在某处看到这个例子

#include <map>
#include <string>

enum responseHeaders
{
    CONTENT_ENCODING,
    CONTENT_LENGTH,
    TRANSFER_ENCODING,
};

// String switch paridgam   
struct responseHeaderMap : public std::map<std::string, responseHeaders>
{
    responseHeaderMap()
    {
        this->operator[]("content-encoding") =  CONTENT_ENCODING;
        this->operator[]("content-length") = CONTENT_LENGTH;
        this->operator[]("transfer-encoding") = TRANSFER_ENCODING;
    };
    ~responseHeaderMap(){}
};

回答by Andrey Syrokomskiy

I use this "tricks" > http://codeproject.com/Articles/42035/Enum-to-String-and-Vice-Versa-in-C

我使用这个“技巧”> http://codeproject.com/Articles/42035/Enum-to-String-and-Vice-Versa-in-C

After

enum FORM {
    F_NONE = 0,
    F_BOX,
    F_CUBE,
    F_SPHERE,
};

insert

插入

Begin_Enum_String( FORM )
{
    Enum_String( F_NONE );
    Enum_String( F_BOX );
    Enum_String( F_CUBE );
    Enum_String( F_SPHERE );
}
End_Enum_String;

Work fine, if values in enum are not dublicate.

如果枚举中的值不重复,则工作正常。

Example in code

代码示例

enum FORM f = ...
const std::string& str = EnumString< FORM >::From( f );

vice versa

反之亦然

assert( EnumString< FORM >::To( f, str ) );

回答by cprogrammer

There is no "built-in way", but there are ways to achieve this by storing the pair value-name in an array

没有“内置方式”,但可以通过将值对存储在数组中来实现这一点

enum myEnum
{
    enumItem0,
    enumItem1,
    enumItem7 = 7,
    enumItem8
};

std::vector<std::pair<myEnum,std::string>>   gMap;

#define ADDITEM(x)  gMap.push_back(std::pair<myEnum,std::string>(x,#x));

.....

.....

ADDITEM(enumItem0);
ADDITEM(enumItem1);
ADDITEM(enumItem7);
ADDITEM(enumItem8);

回答by Mara Black

this worked for me:

这对我有用:

enum NODES { Cone = 1, BaseColor = 2, NONE = 0 };

std::map<std::string, NODES> nodeMap;
nodeMap["Cone"] = NODES::Cone;
nodeMap["BaseColor"] = NODES::BaseColor;

回答by jj1

You can use macro to minimize repeating yourself. Here is the trick: Enums, Macros, Unicode and Token-Pasting

您可以使用宏来最大程度地减少重复自己。诀窍是:枚举、宏、Unicode 和令牌粘贴

回答by Constantinius

In short: there is none. In C++ enums are static values and not objects like in C#. I suggest you use a function with some if elsestatements.

简而言之:没有。在 C++ 中,枚举是静态值,而不是像 C# 中的对象。我建议您使用带有一些if else语句的函数。

回答by Alexander Sulfrian

It is not possible because the names are not available at runtime. During compilation each enum is replaced with the corresponding integer value.

这是不可能的,因为名称在运行时不可用。在编译期间,每个枚举都被替换为相应的整数值。

回答by TeaWolf

While there is no direct solution, there are a few possible workarounds.

虽然没有直接的解决方案,但有一些可能的解决方法。

Take a look at this question: Easy way to use variables of enum types as string in C?

看看这个问题:Easy way to use enum types of variables as string in C?