8

我正在寻找将 avector<string>和一个boost::unordered_map<string, size_t>映射字符串替换为前者中的索引boost::bimap

我应该使用什么实例化bimap?到目前为止,我想出了

typedef bimap<
    unordered_set_of<size_t>,
    vector_of<string>
> StringMap;

但我不确定我现在是否已经反转了集合类型。另外,我想知道是否应该更改关系类型的集合。avector_of_relation是我最好的选择,还是 a set_of_relation,或者只是使用默认值?

4

1 回答 1

4

要在 size_t 和 std::string 之间获得一个 bimap,其中您有 ~constant(直至散列成本和任何潜在冲突),您需要使用 unordered_set_of:

#include <boost/bimap.hpp>
#include <boost/bimap/unordered_set_of.hpp>
#include <string>
#include <iostream>
#include <typeinfo>

int main(int argc, char* argv[]) {

  typedef boost::bimap< boost::bimaps::unordered_set_of<size_t>, boost::bimaps::unordered_set_of<std::string> > StringMap;
  StringMap map;
  map.insert(StringMap::value_type(1,std::string("Cheese")));
  map.insert(StringMap::value_type(2,std::string("Cheese2")));

  typedef StringMap::left_map::const_iterator const_iter_type;
  const const_iter_type end = map.left.end();

  for ( const_iter_type iter = map.left.begin(); iter != end; iter++ ) {
    std::cout << iter->first << " " << map.left.at(iter->first) << "\n";
  }

}

返回:

1 Cheese
2 Cheese2

unordered_set 是 set 的 boost 版本,它使用哈希表而不是树来存储元素,请参阅Boost Unordered 文档

查看来自Bimap 示例中的一个 bimap 示例的评论,我们有:

左侧地图视图的工作方式类似于 std::unordered_map< std::string, long >,给定国家名称,我们可以使用它在恒定时间内搜索人口

于 2011-06-03T21:21:21.600 回答