【问题标题】:Replace vector and hash table with Boost.Bimap用 Boost.Bimap 替换向量和哈希表
【发布时间】:2010-11-16 13:12:57
【问题描述】:

我希望用 boost::bimap 替换 vector<string>boost::unordered_map<string, size_t> 映射字符串到前者的索引。

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

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

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

【问题讨论】:

  • 添加更多关于您计划使用数据的方式的信息,以便我们确定完成您需要的限制。
  • 我希望在 size_tstring 对象之间进行双射,同时满足 O(1) 访问时间和最小或适中的内存需求。
  • @rep_movsd:是的,他们是。我最终通过使用 Boost.MultiIndex 解决了这个问题,我发现它更容易理解。 (事实证明我需要第三个数据视图:stackoverflow.com/questions/4217885/…)不过,仍然欢迎回答。

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


【解决方案1】:

要在 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 Unordered docs

Bimap example 的一个 bimap 示例中查看 cmets,我们有:

左侧地图视图的工作方式类似于 std::unordered_map, 给定国家的名称,我们可以用它来搜索常数时间的人口

【讨论】:

  • 但这会给我 O(1) 的访问时间来访问 size_t 一侧并从另一侧获得“散列 O(1)”吗?
  • 不,它不会有。虽然希望这可以通过我最近的编辑得到纠正。我怀疑访问(size_t 或 std::string)以这种方式在最坏的情况下得到 O(1),但他们应该得到 O(1) 的平均情况复杂度。
  • 好的,接受。不过,我会向 Bimap 的任何潜在用户推荐 MultiIndex。
猜你喜欢
  • 1970-01-01
  • 2011-06-03
  • 2017-11-03
  • 2013-07-21
  • 1970-01-01
  • 2011-11-19
  • 1970-01-01
  • 1970-01-01
  • 2016-07-14
相关资源
最近更新 更多