问题描述
在C ++中有一个简单的方法将字符串转换为枚举(类似于C#中的 Enum.Parse
)?
Is there a simple way in C++ to convert a string to an enum (similar to Enum.Parse
in C#)? A switch statement would be very long, so I was wondering if there is a simpler way to do this?
编辑:
感谢您的所有回复。我意识到有一个更简单的方法来做我的特定情况。字符串总是包含字符'S'后面跟一些数字,所以我只是
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
int i = atoi(myStr.c_str() + 1);
然后在i上做了一个开关。
and then did a switch on i.
推荐答案
std :: map< std :: string,MyEnum>
(或 unordered_map
)可以轻松做到。填充地图将像switch语句一样枯燥乏味。
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.
这篇关于C ++字符串到枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!