In C , developers often encounter the need to translate strings into enums. A naive approach would be to employ a lengthy switch statement. However, more convenient methods exist.
One solution is a mapping using a standard library map, which establishes a correspondence between strings and enums. While this can be effective, it requires meticulous initialization.
With the advent of C 11, a more streamlined approach is available. Using an unordered map, you can construct a table mapping strings to enums during the compilation phase:
static std::unordered_map<std::string,E> const table = { {"a",E::a}, {"b",E::b} };
Retrieving the corresponding enum for a given string is now straightforward:
auto it = table.find(str); if (it != table.end()) { return it->second; } else { // Handle error }
The above is the detailed content of How to Convert C Strings to Enums Efficiently?. For more information, please follow other related articles on the PHP Chinese website!