I have an enumeration, which contains hundreds of entries.
I will be getting the value of the enumeration as a string. Is there any way to convert the string into an enum value? Otherwise, I will end up using hundreds of if statements.
Consider
enum Colors { Red, Green, Blue, Yellow ... } there are more than 100 entries
I will be getting "Red"
in a string variable,
String color = "Red"; // "Red" would be generated dynamically.
Normally we access the enum in the following way,
Colors::Red
, Colors::Blue
etc...
is there any way in which we can access it in a way something like this:
Colors::color; // i.e enumtype::stringVariable
In many posts here, it’s given that we can use map, but again while constructing map we will end up in using hundreds of if
s.
Is there any way to avoid this?
Here's a C way of doing it, similar to Paddy's C++ map. The macro guarantees that the name and corresponding enum are tied together.
enum Colors { NoColor, Red, Green, Blue, Yellow };
enum Colors get_color(const char *s)
{
const struct {
char *name;
enum Colors color;
} colormap[] = {
#define Color(x) {#x, x}
Color(Red),
Color(Green),
Color(Blue),
Color(Yellow)
#undef Color
};
for (size_t i = 0; i < sizeof colormap / sizeof colormap[0]; ++i) {
if (!strcmp(s, colormap[i].name)) {
return colormap[i].color;
}
}
return NoColor;
}
#define COLORS X(Red), X(Green), X(Blue), X(Yellow),
enum Colors {
NoColor,
#define X(x) x
COLORS
#undef X
};
enum Colors get_color(const char *s)
{
const struct {
char *name;
enum Colors color;
} colormap[] = {
#define X(x) {#x, x}
COLORS
#undef X
};
...etc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With