如何迭代地图并将其键值与枚举 class 成员匹配?

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

我有一个简短的问题。

是否有任何技巧可以遍历映射的键并使用它们来访问枚举 class 个项目。

例如,假设我们有如下定义的颜色 class。

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. 是否有比使用 if/else-if 调用方法 fGetVal 更好的方法?
  2. 更具体地说,尝试使用变量名来访问枚举 class 元素,例如 Color::e.first

您是否尝试将用户输入转换为 Color 枚举

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;
}

一个干净的方法是 pre-cache 在地图中 fGetVal() 的结果,然后做一个简单的查找:

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!";
    }
  }
}