Home >Backend Development >C++ >How to Convert a String to an Enum in C ?

How to Convert a String to an Enum in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-11 04:13:03523browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn