简体   繁体   中英

Using enum value as a entry in a map in c++

I have an enum:

enum FlowType {

        LEVEL_FLOW = 1,
        PARTITION_FLOW = 3,
        ORDERBOOK_EVENT_FLOW = 4
}

I want to create a map such that on searching the integer part above, I must get the "LEVEL_FLOW" part back.

I am unable to come up with the map declaration and insertion statements. Please help.

This is waht I tried:

std::map<int, FlowType > FlowsMap;
FlowsMap.insert(std::make_pair<1, FlowType.LEVEL_FLOW >);

If you want to add values:

typedef enum e
{
    ONE = 1,
    TWO = 2,
    THREE = 3
} etype;

int main(int arc, char **argv)
{
    std::map <etype, std::string> mmap;
    mmap[THREE] = 3;
}

You should use just LEVEL_FLOW not FlowType.LEVEL_FLOW , if the enum is in the same scope. Otherwise, specify the scope, too.

The problem you are facing with insertion lay in your syntax. You should write :

FlowsMap.insert(std::make_pair(1, FlowType.LEVEL_FLOW));  
// make_pair is a function (make_pair()), pair is a type (pair <>)

or more nicely

FlowsMap[1] = LEVEL_FLOW; 

There is no need to overload comparison operator for the value item in your map. Moreover, even if your key were to be the FlowType enum it would not be needed.

However I wonder if you really need a map for this... when you can cast your int in your enum type:

int myInt = 1;
FlowType ft = static_cast<FlowType> (myInt);

The only issue would be the case when some int has no enum value associated. You can prevent this with your map by using the find() method. If you know that case will not happen you can consider avoiding map use.

Note that you are using C-style enums.

If you want to stick to them, you can fix it by changing your code to:

FlowsMap.insert(std::make_pair<1, LEVEL_FLOW >);

If you want the enum name to become part of the scope (like you are trying in your example), have a look at this thread on C++-style enums .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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