Efficient Conversion of Strings to Enums in C
When working with enums in C , you may encounter the need to convert strings to their corresponding enum values. While a switch statement can suffice, it can become cumbersome with numerous enum values. This article explores alternative approaches for efficient string-to-enum conversion.
std::map Solution
One approach is to create a std::map
C 11 Syntactic Sugar
For C 11 and later, a more concise solution becomes available. Using statically initialized std::unordered_map, you can populate the map elegantly using curly braces:
static std::unordered_map<std::string,E> const table = { {"a",E::a}, {"b",E::b} };
To perform the lookup, simply use the find() method on the table and check if the iterator is valid. If found, you can retrieve the corresponding enum value directly.
Example
For instance, consider the following enum declaration:
enum class E { a, b, c };
And a string "a", you can convert it to the corresponding enum value using the table:
auto it = table.find("a"); if (it != table.end()) { E result = it->second; // ... }
This approach provides a concise and efficient solution for converting strings to enums in C , reducing the complexity of long switch statements.
The above is the detailed content of How to Efficiently Convert Strings to Enums in C ?. For more information, please follow other related articles on the PHP Chinese website!