boost :: bimap枚举 [英] boost::bimap for enum

查看:193
本文介绍了boost :: bimap枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为C ++中的枚举创建一个简单的双向查找工具。我有单向查找工作正常...

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");

然后通过

MyEnumMap.at(One)

用于基于键的查找。我想使用一个双向查找容器,如boost:bimap,以允许基于值和键的简单的反向查找。它似乎不像map_list_of兼容boost :: bimap虽然。

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.

首先,我仍然使用map_list_of与boost :: bimap,或是另一种类型所需?

这些映射将是一个基本的(枚举,字符串)类型。

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.

其次,有一种方法, const在一个简单的方法如上?我试图使这很容易更新和维护尽可能不用太多额外的typedefs等。

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.

推荐答案

尝试直接使用list_of:

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" );

请注意relation而不是value_type的用法。

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

这篇关于boost :: bimap枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆