Home >Backend Development >C++ >How to Convert C Strings to Enums Efficiently?

How to Convert C Strings to Enums Efficiently?

Linda Hamilton
Linda HamiltonOriginal
2024-11-12 07:33:01723browse

How to Convert C   Strings to Enums Efficiently?

Converting C Strings to Enums

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!

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