简体   繁体   English

在C ++中将枚举值用作映射中的条目

[英]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. 我想创建一个地图,以便在搜索上面的整数部分时,必须返回“ LEVEL_FLOW”部分。

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. 如果enum在同一范围内,则应仅使用LEVEL_FLOW而不是FlowType.LEVEL_FLOW 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. 而且,即使您的键是FlowType枚举,也将不需要它。

However I wonder if you really need a map for this... when you can cast your int in your enum type: 但是我想知道您是否真的需要一个地图...何时可以将您的int转换为枚举类型:

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

The only issue would be the case when some int has no enum value associated. 唯一的问题是某些int没有关联的枚举值的情况。 You can prevent this with your map by using the find() method. 您可以使用find()方法在地图上防止这种情况。 If you know that case will not happen you can consider avoiding map use. 如果您知道这种情况不会发生,可以考虑避免使用地图。

Note that you are using C-style enums. 请注意,您正在使用C风格的枚举。

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 . 如果您希望枚举名称成为作用域的一部分(就像您在示例中尝试的那样),请查看C ++样式枚举上的该线程

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

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