代码之家  ›  专栏  ›  技术社区  ›  Fred Foo

用Boost.Bimap替换向量和哈希表

  •  8
  • Fred Foo  · 技术社区  · 15 年前

    我想换一个 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 ,还是只使用默认值?

    1 回复  |  直到 15 年前
        1
  •  4
  •   MGwynne    15 年前

    若要在size_t和std::string之间获取bimap,其中有~常量(不超过散列和任何潜在冲突的成本),则需要使用无序集合:

    #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
    

    无序集是set的boost版本,它使用哈希表而不是树来存储元素,请参见 Boost Unordered docs .

    查看bimap示例中的评论 Bimap example ,我们有:

    左映射视图的工作方式类似于std::无序映射<std::string,long>, 鉴于这个国家的名字,我们可以用它在固定的时间内搜寻人口

    推荐文章