繁体   English   中英

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

[英]iterate through all enum variants of a given enum

是否可以遍历给定枚举的所有枚举变体。 我有一个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仍然可以工作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM