Home >Backend Development >C++ >How to Convert a String to an Enum in C ?
Converting String to Enum in C
In C , there is no direct equivalent to C#'s Enum.Parse for converting strings to enums. One common solution is to use a switch statement, but for large enum lists, this approach becomes unwieldy.
Using a Map or Unordered Map
An elegant solution is to utilize a std::map or std::unordered_map to associate string keys with corresponding enum values. This allows for efficient lookup and retrieval.
std::unordered_map<std::string, MyEnum> enumMap { {"foo", MyEnum::Foo}, {"bar", MyEnum::Bar} };
To convert a string to an enum:
MyEnum myEnum = enumMap[myString];
Trivial Initialization with C 11
With C 11 and later, populating the map can be significantly simplified:
static std::unordered_map<std::string, MyEnum> const table = { {"a", MyEnum::a}, {"b", MyEnum::b} };
Then, to retrieve the enum value:
auto it = table.find(myString); if (it != table.end()) { return it->second; } else { // Handle error }
The above is the detailed content of How to Convert a String to an Enum in C ?. For more information, please follow other related articles on the PHP Chinese website!