简体   繁体   English

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

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

Is it possible to iterate through all enum variants of a given enum.是否可以遍历给定枚举的所有枚举变体。 I have an std::unordered_map<Enum, Value_Type> with enum variant as key.我有一个std::unordered_map<Enum, Value_Type> ,其中枚举变量作为键。 I need to check whether all the enum variants of a given enum exist as key in std::unordered_map<Enum, Value_Type> .我需要检查给定枚举的所有枚举变体是否作为键存在std::unordered_map<Enum, Value_Type>

Consider making a helper method like AllKeyPresent illustrated in a sample program below考虑制作一个像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;
}

I would also recommend declaring your enum like this enum DIR : int {DIR_FIRST, NORTH, SOUTH, WEST, EAST, DIR_LAST};我还建议像这样声明你的枚举enum DIR : int {DIR_FIRST, NORTH, SOUTH, WEST, EAST, DIR_LAST}; where DIR_FIRST and DIR_LAST are just dummy entries, and change for loop iteration to for (int key = DIR::DIR_FIRST + 1; key < DIR:DIR_LAST; key++) .其中 DIR_FIRST 和 DIR_LAST 只是虚拟条目,并将 for 循环迭代更改为for (int key = DIR::DIR_FIRST + 1; key < DIR:DIR_LAST; key++) This way, if someone decides to add a new entry to your enum like SOUTHWEST , then AllKeysPresent will still work这样,如果有人决定向您的枚举添加一个新条目,例如SOUTHWEST ,那么AllKeysPresent仍然可以工作

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

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