Home > Enterprise >  How to iterate over a map and match its key values with enum class members?
How to iterate over a map and match its key values with enum class members?

Time:04-13

I have a quick question.

Is there any trick to iterate through the keys of a map and use them to access an enumerate class items.

For example, lets say we have the Color class as defined below.

enum class Color {blue = 0, green = 1, yellow = 2};

unordered_map<string, string> mp {
  {"blue",""},
  {"green",""},
  {"yellow",""},
  {"red", ""}
 };

for (auto e: mp) {
   if(e.first.compare("blue") ==0) { // e.first == "blue"
       e.second = fGetVal(Color::blue); 
    } else if (e.first.compare("green") ==0) { 
       e.second = fGetVal(Color::green); 
    } else if (e.first.compare("yellow") ==0) {
       e.second = fGetVal(Color::yellow); 
    } else {
       cout<<"the requested color is not supported!"
    }
}

//  assume fGetVal() takes the enum class type as input and returns it value as a string
  1. Is there a better approach than using if/else-if to call method fGetVal?
  2. More specifically trying to use a variable name for accessing enum class elements something like Color::e.first

CodePudding user response:

Are you trying to convert user input input a Color enum

enum class Color { blue = 0, green = 1, yellow = 2 };

unordered_map<string, Color> mp{
  {"blue",Color::blue},
  {"green",Color::green},
  {"yellow",Color::yellow},
};

string col = getUserInput();
auto find = mp.find(col);
if (find == mp.end()) {
    cout << "bad color";
}
else {
    auto encol = find->second;
}

CodePudding user response:

An clean way to do is is to pre-cache the results of fGetVal() in a map and just do a simple lookup:

const unordered_map<string, string> colorStringsMap = {
 {"blue", fGetVal(Color::blue)},
 {"green", fGetVal(Color::green)},
 {"yellow", fGetVal(Color::yellow)},
};


int main() {
  unordered_map<string, string> mp {
    {"blue",""},
    {"green",""},
    {"yellow",""},
    {"red", ""}
   };

  for (auto e: mp) {
    try {
      e.second = colorStringsMap.at(e.first);
    }
    catch(std::out_of_range) {
      cout <<"the requested color is not supported!";
    }
  }
}
  • Related