遍历给定枚举的所有枚举变体

  • 本文关键字:枚举 遍历 c++ enums
  • 更新时间 :
  • 英文 :


是否有可能遍历给定枚举的所有枚举变体?我有一个以枚举变量为关键的std::unordered_map<Enum, Value_Type>。我需要检查给定枚举的所有枚举变体是否在std::unordered_map<Enum, Value_Type>中作为键存在。

考虑创建一个像下面示例程序中所示的AllKeyPresent这样的辅助方法

#include <iostream>
#include <unordered_map>
//declare an enum
enum DIR : int {NORTH, SOUTH, WEST, EAST}; 
/**
* AllKeysPresent: return true if and only if map contains all enum keys
*/
template<typename T = int> 
bool AllKeysPresent(const std::unordered_map<DIR, T>& myMap)
{
bool allKeysPresent = true;
//loop over enum, starting with the first entry up and including the last entry
for (int key = DIR::NORTH; key <= DIR::EAST; key++)
{
if (myMap.find(static_cast<DIR>(key)) == myMap.end())
{
allKeysPresent = false;
break;
}
}
//TODO: check if at least one valid key is present. return false if the map is empty
return allKeysPresent;
}
int main()
{
//make a map with all keys
std::unordered_map<DIR, int> mapWithAllKeys = { {DIR::NORTH, -1}, {DIR::SOUTH, -2}, {DIR::WEST, -3}, {DIR::EAST, -4} };
std::unordered_map<DIR, int> mapWithSomeKeys = { {DIR::NORTH, -1}, {DIR::SOUTH, -2} };
std::cout << AllKeysPresent(mapWithAllKeys) << std::endl;
std::cout << AllKeysPresent(mapWithSomeKeys) << std::endl;
return 0;
}

我还建议像这样声明枚举enum DIR : int {DIR_FIRST, NORTH, SOUTH, WEST, EAST, DIR_LAST};其中DIR_FIRST和DIR_LAST只是虚拟条目,并将for循环迭代更改为for (int key = DIR::DIR_FIRST + 1; key < DIR:DIR_LAST; key++)。这样,如果有人决定在你的枚举中添加一个新条目,比如SOUTHWEST,那么AllKeysPresent仍然会工作

最新更新