【问题标题】:Create links between elements in two vectors在两个向量中的元素之间创建链接
【发布时间】:2013-06-11 21:23:40
【问题描述】:

我计划制作链接以识别两个向量的关联。 假设我们有两个向量:

vector1 <seg1, seg2, seg3>
vector2 <pic1, pic2, pic3,pic4>

并且假设关联如下:

seg1->(pic1, pic2) seg2->(pic1,pic2) seg3->pic3 //from vector1 side
pic1->(seg1, seg2) pic2->(seg1,seg2) pic3->seg3 pic4->nothing //from vector2 side

我想要知道哪个 seg 与哪个 indexNums 图片相关联,对于图片也是如此。我只关注两个向量中的位置编号,并不关心这两个向量的元素内容是什么。我所做的是设计一个类似的结构:

Struct 
{
  int indexNum;
  Bool type; //seg or pic
  addlink(indexNum); //add a link to another Struct, and the type should be opposite.
  removelink(indexNum); //remove a link from a given indexNum
  getLinks();  //return all of links, the return should be vector<Struct*>? 
}

我觉得不好,对协会也不清楚。有没有更好的方法为这两个向量建立链接?

【问题讨论】:

    标签: c++ design-patterns data-structures


    【解决方案1】:

    Boost.Bimap 旨在解决此类问题。

    【讨论】:

    • 谢谢,我有一个关于在我的案例中使用 bimap 的问题。如果我插入(seg3,pic3),这很酷,双重搜索。但是对于 (seg2,) 的情况,如何存储,我需要存储 (seg2,pic2),(seg2,pic3)?合适吗?还是我错过了什么?
    • 是否可以重复键?非常感谢!
    • @CJAN.LEE:是的。见here
    【解决方案2】:

    我想知道 multimap 是否适合您

    http://www.cplusplus.com/reference/map/multimap/

    【讨论】:

      【解决方案3】:
      #include <iostream>
      #include <boost/bimap.hpp>
      #include <boost/bimap/set_of.hpp>
      #include <boost/bimap/multiset_of.hpp>
      
      namespace bimaps = boost::bimaps;
      
      int main()
      {
         typedef boost::bimap<bimaps::multiset_of<int>, bimaps::set_of<int>> bimap_t;
         typedef bimap_t::value_type value_type;
         bimap_t bimap;
         bimap.insert(value_type(1, 1));
         bimap.insert(value_type(1, 2));
         auto& left = bimap.left;
         auto it = left.find(1);
         std::cout << "LEFT" << std::endl;
         for (; it != left.end(); ++it)
         {
            std::cout << it->first <<  " " << it->second << std::endl;
         }
         auto& right = bimap.right;
         auto r_it = right.find(2);
         std::cout << "RIGHT" << std::endl;
         for (; r_it != right.end(); ++r_it)
         {
            std::cout << r_it->first << " " << r_it->second << std::endl;
         }
      }
      

      http://liveworkspace.org/code/e766b134d9e96b9192424ac9325ae59c

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-03
        • 1970-01-01
        • 2021-06-18
        • 2011-08-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多