【问题标题】:c++ efficient data structure for bidirectional random access用于双向随机访问的 c++ 高效数据结构
【发布时间】:2012-11-05 00:36:53
【问题描述】:

我有两个集合 A 和 B 的元素 a 和 b。现在它们彼此相关(0..1:n 基数),所以每个 a 在 B 中最多有一个伙伴,每个 b 可以有几个(在至少一个)与 A 中项目的关联。 A 是一组整数对,B 是整数。

有没有有效的方法来存储这样的“双向”地图? 一个简单的方法是使用两个地图:

map<pair<unsigned int, unsigned int>, unsigned int> AtoB
map<unsigned int, vector<pair<unsigned int, unsigned int> > > BtoA

但也许有更好的方法来更有效地处理这个问题。

感谢您的帮助

【问题讨论】:

    标签: c++ data-structures map


    【解决方案1】:

    boost::bimap 怎么样? http://www.boost.org/doc/libs/1_47_0/libs/bimap/doc/html/index.html我想是给你的。

    【讨论】:

      【解决方案2】:

      Boost 包含两个库来处理这个问题:Boost.BimapBoost.MultiIndex。前者专门针对双射(“双向”)映射问题,而第二个更通用,实现类似于具有任意索引的内存数据库。

      鉴于您的 unsigned int 键不会唯一地映射到您的对,我认为 MultiIndex 更有序。自从我上次使用这个库以来已经很长时间了,但是看看教程,你需要类似的东西

      struct YourData {
           unsigned key;
           std::pair<unsigned, unsigned> value;
      };
      
      typedef multi_index_container<
          YourData,
          indexed_by<
              ordered_non_unique<member<YourData, unsigned, &YourData::key> >,
              ordered_unique<member<YourData, std::pair<unsigned, unsigned>,
                                    &YourData::value> >
          >
      > YourContainer;
      

      如果您不想使用 Boost,那么您至少可以通过替换来简化当前设置

      map<unsigned int, vector<pair<unsigned int, unsigned int> > >
      

      std::multimap&lt;unsigned, std::pair&lt;unsigned, unsigned&gt;&gt;

      【讨论】:

        【解决方案3】:

        Map 和 Multimap 的效率为 O(log n),因此,我认为这是存储数据的最佳方式。我建议使用

        map<pair<unsigned int, unsigned int>, unsigned int> AtoB
        multimap<pair<unsigned int, unsigned int>, unsigned int> BtoA
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-10-27
          • 2013-02-22
          • 1970-01-01
          • 2020-10-06
          • 2015-08-01
          • 1970-01-01
          • 2013-04-06
          • 1970-01-01
          相关资源
          最近更新 更多