boost::bimap for enum

旧时模样 提交于 2019-12-06 01:41:34

问题


I'm trying to create a simple bi-directional lookup facility for enums in C++. I have one-way lookup working fine...

enum MyEnum
{ 
    One, 
    Two, 
    Three 
};

const boost::unordered_map<MyEnum,std::string> MyEnumMap = map_list_of
    (One, "One")
    (Two, "Two")
    (Three, "Three");

and then doing a look via

MyEnumMap.at(One)

That works but it only allows for lookups based on key. I'd like to use a bi-directional lookup container such as boost:bimap to allow for easy reverse lookups based on value as well as key. It doesn't seem like map_list_of is compatible with boost::bimap though.

Firstly, should I still be using map_list_of with boost::bimap, or is another type required?
The maps will all be a basic (Enum, string) type.

Second, is there a way I can still define the map as const in a simple way as above? I'm trying to make this as easy to update and maintain as possible without getting into too many additional typedefs and such. Your insight is appreciated.


回答1:


Try using list_of directly:

typedef boost::bimap< MyEnum, std::string > bm_type;
const bm_type MyEnumMap =
  boost::assign::list_of< bm_type::relation >
    ( One, "One" )
    ( Two, "Two" )
    ( Three, "Three" );

Note the usage of 'relation' instead of 'value_type'.



来源:https://stackoverflow.com/questions/10745664/boostbimap-for-enum

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!