Boost::bimap

Boost.Bimap 是一个C++的双向 map 库。使用 Boost.Bimap,你可以创建两个类型都可用作键值的关联容器。bimap<X,Y> 可以被视为 std::map<X,Y> 加上 std::map<Y,X>。如果你知道如何使用标准容器,那么 bimap 的学习曲线就几乎是平的。在 Boost.Bimap 中作出了大量的努力,以符合STL的命名规则。本库是按照与常见STL容器相匹配的方式进行设计的。

记住,bm 可单独用作关系的 set。我们可以插入元素,或者使用该视图进行遍历。

boost::bimap - 双向映射

定义一个 bimap :

#include bimap bm;

它有3个不同的视图:

bm.left : 是一个兼容于 std::map 类型的东西.

bm.right: 是一个兼容于 std:::map 类型的东西.

bm 是一个兼容于 std::set< relation 类型的东西.

 例如我们有一个输出map的函数如下:

template< class MapType > void print_map(const MapType & m)

{

      typedef typename MapType::const_iterator const_iterator;

     for( const_iterator iter = m.begin(), iend = m.end(); iter != iend; ++iter )

      {

         std::cout << iter->first << "-->" << iter->second << std::endl;

       }

}

它的参数可以接受一个 std::map 对象. 所以它也可以接受如下调用:

print_map( bm.left );

print_map( bm.right );

下边我们定义一个整数和字符串的双向映射: 

typedef boost::bimap< int, std::string > bm_type;

 bm_type bm;

向其插入数据:

bm.insert( bm_type::value_type(1, "one" ) );

bm.insert( bm_type::value_type(2, "two" ) );

 输出刚才插入的数据:

 std::cout << "There are " << bm.size() << "relations" << std::endl; for( bm_type::const_iterator iter = bm.begin(), iend = bm.end(); iter != iend; ++iter )

 {

 std::cout << iter->left << " <--> " << iter->right << std::endl;

 }

接着我们使用它的 left 视图(就像在使用一个std::map): //left视图的迭代器类型

 typedef bm_type::left_map::const_iterator left_const_iterator;

for( left_const_iterator left_iter = bm.left.begin(), iend = bm.left.end(); left_iter != iend; ++left_iter )

{

   std::cout << left_iter->first << " --> " << left_iter->second << std::endl;

}

bm_type::left_const_iterator left_iter = bm.left.find(2);

assert( left_iter->second == "two" ); // 再通过左视图向 bm 插入数据 //

它和直接用 bm.insert( bm_type::value_type(3,"three") ); 效果一样

bm.left.insert( bm_type::left_value_type( 3, "three" ) );

同样的. 我们可以使用它的 right视图 : // 通过 string 查找

bm_type::right_const_iterator right_iter = bm.right.find("two"); assert( right_iter->second == 2 ); // 调用 at() assert( bm.right.at("one") == 1 ); // 删除 "two" 对应的关系 bm.right.erase("two");

 最后. 缺省时在 std::map 中. 我们插入 ("1", 1) 后再插入 ("one", 1) 是可以的.

但这在bimap中不行. 因为它左右两个都可以做键值. 要求它们两者都必须是唯一的. 但这只是它缺省时的样子. bimap可以通过模板参数来定制它一些特征: 例如可以指定是否需要 一对多 的映射关系: 可以一个 x 对应多个 y. 可以多个 x 对应一个 y. 也可以多个 x 对应多个 y. 还可以指定是否要求 left视图 或 right视图 或 两者 有序. 如果不要求有序的话. 它可以用 hash表来实现底层.

原文地址:https://www.cnblogs.com/kex1n/p/2286505.html