c++ - 用 Boost.Bimap 替换 vector 和哈希表

标签 c++ data-structures boost unordered-map bimap

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

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

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

但我不确定我现在是否已经颠倒了集合类型。另外,我想知道我是否应该更改 collection of relations type .会 vector_of_relation是我最好的选择,或者set_of_relation ,还是只使用默认值?

最佳答案

要获得 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 docs .

查看来自 Bimap example 的一个双图示例的评论,我们有:

The left map view works like a std::unordered_map< std::string, long >, given the name of the country we can use it to search for the population in constant time

关于c++ - 用 Boost.Bimap 替换 vector 和哈希表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4194468/

相关文章:

c++ - 如何在C++中使用 "type ... pack-name"参数包?

c++ - 如何正确使用C++ 11风格的内存池?

data-structures - B 树中的最大和最小键数

c++ - 以下代码中的功能模板有什么问题?

c++ - boost::any 库不编译: "Array used as initializer"错误

c++ - 谁能解释一下这个图像分辨率设置代码?这到底是怎么回事

c++ - 如何使用 MinGW 生成器从 powershell 调用 cmake

java - 为什么我应该使用 Deque 而不是 Stack?

c++ - R* 树重叠计算

即使是基本的东西,Boost 也需要像 libboost_date_time 这样的编译库。如何消除对构建这些库的依赖?