我想更换一个 vector<string>boost::unordered_map<string, size_t> 将字符串映射到前者的索引 boost::bimap.

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

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

但是我不确定现在是否逆转了收藏类型。另外,我想知道我是否应该更改 关系类型的收集. 。会 vector_of_relation 成为我的最佳选择,或 set_of_relation, ,还是只使用默认值?

有帮助吗?

解决方案

要获得size_t和std ::字符串之间的bimap,您需要使用〜常数(达到哈希的成本和任何潜在冲突),您需要使用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的提升版本,该版本使用哈希表代替树来存储元素,请参阅 提升无序文档.

查看来自BIMAP示例之一的评论 BIMAP示例, , 我们有:

左图视图就像std :: unordered_map <std :: string,long>,给定国家的名称,我们可以在恒定时间内使用它来搜索人口

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top