boost bimap简介

来源:互联网 发布:js中什么时候用bind 编辑:程序博客网 时间:2024/05/22 15:45

        很多人都熟悉c++ stl,各种各样的容器vector, list, set这些,还有一些算法find, binary_search, sort等等给我们编程的时候提供了很多方便。但是有时候在使用的时候还是感觉到有点不足,例如循环使用的buffer, 智能指针,类似java里面的foreach,这些都在stl库里面没有,如果要自己实现的话,设计开发测试起来挺麻烦的。有一个开源的类似于stl的程序库boost,是对stl很好的补充,其中提供了一些常用的但是stl还没有提供的容器,算法等。那些都是经过了严格的开发,性能测试,可以很放心的使用。boost库中有很多已经进入了c++标准委员会的Library Technical Report中了,将来可能会正式进入到stl中去,到时候就可以像使用stl中的东西一样使用boost中的一些项目了。

        boost中的东西已经很多了,要在一篇文章中介绍所有的项目不太可能,这里我只简单介绍一下boost中的双向映射容器bimap。我们都知道stl的map是从key -> value的映射,其中key不能重复(multimap除外), 从key可以快速查找到value。但是如果我们想从key查找value, 同时也想从value查找key的话,map就不能满足我们的需求了。这时候boost的bimap就可以派上用场了。它实现了KeySet到ValueSet的一个双向映射,而且查找的效率也是比较高的。内部的实现bimap看起来好像用了两个map, 一个实现从key -> value的映射,另外一个实现从value -> key的映射。下面我们通过简单的例子说明:

#include "boost/bimap.hpp"
#include <iostream>
#include <string>

using namespace std;

typedef boost::bimap<int, string> bm_type;   //给boost::bimap<int, string>起一个别名bm_type
 //bimap看起来有两个map, 一个bimap.left, 一个bimap.right, 对应的迭代器
//分别是left_iterator, right_iterator

typedef bm_type::left_const_iterator left_const_iterator;   
typedef bm_type::right_const_iterator right_const_iterator; 

int main(int argc[], char* argv[]) {
  bm_type userIdToUrl;
  //bimap兼容map的大多数操作,urlIdToUrl.insert()和urlIdToUrl.left.insert的效果是一样的,但是建议使用bimap.left.insert
  //其中避免了一些转换,效率上会有一点提高
  userIdToUrl.insert(bm_type::value_type(1, "url1"));
  userIdToUrl.insert(bm_type::value_type(2, "url2"));
  left_const_iterator left_iter = userIdToUrl.left.find(2);
   if (left_iter != userIdToUrl.left.end()) {
    cout << left_iter->first << " " << left_iter->second << endl;
  }
  right_const_iterator right_iter = userIdToUrl.right.find("url1");
  if (right_iter != userIdToUrl.right.end()) {
    cout << right_iter->first << " " << right_iter->second << endl;
  }
  return 0;
}

      这里只介绍了bimap最简单的用法,当然bimap的功能远比这个要强大很多。 其中我觉得一个特性很有用,Additional Information,就是可以在两个双向映射上k1<-->v1上加上一些辅助的信息。简单的示例如下:

#include "boost/bimap.hpp"
#include "boost/config.hpp"
#include <iostream>
#include <string>

using namespace std;
using namespace boost::bimaps;

typedef boost::bimap<int, string, with_info<string> > bm_type;
typedef bm_type::left_const_iterator left_const_iterator;
typedef bm_type::right_const_iterator right_const_iterator;

int main(int argc[], char* argv[]) {
  bm_type userIdToUrl;
  userIdToUrl.insert(bm_type::value_type(1, "url1", "this is a relation (1, \"url1\")"));
  left_const_iterator left_iter = userIdToUrl.left.find(1);
  cout  << left_iter->first << " " << left_iter->second << " : " << left_iter->info << endl;
  return 0;
}

       有关bimap详细的设计和使用,可以查阅http://www.boost.org/doc/libs/1_42_0/libs/bimap/doc/html/index.html

原创粉丝点击