【问题标题】:How to override the uniqueness and order of a std::set<std::pair<int, int>> in c++?如何在 c++ 中覆盖 std::set<std::pair<int, int>> 的唯一性和顺序?
【发布时间】:2021-10-11 21:47:14
【问题描述】:

我正在尝试在 c++ 中创建一个 std::set 的 std::pair 。我希望集合显示的行为是使用对的第一个元素对对进行排序,并使用对的第二个元素定义不规则性。例如,如果输入对如下:

1 5
5 2
3 3
2 4
4 3

该集合应如下所示:

1 5
2 4
4 3
5 2

【问题讨论】:

标签: c++ stl set std-pair


【解决方案1】:

使用std::set 无法做到这一点。 std::set 使用与订单相同的相等关系,没有任何技巧可以改变它。

【讨论】:

  • 感谢您的信息。那么是否有其他 stl 容器能够做到这一点?
  • @DivyanshFalodiya 没有。我认为boost::multi_index_container 可以。
【解决方案2】:

您可以使用地图来制作唯一性。

#include <iostream>
#include <set>
#include <map>

using p = std::pair<int, int>;

int main(){
    std::set<p> s {
        {1, 5},
        {5, 2},
        {3, 3},
        {2, 4},
        {4, 3}
    };
    // copy to a map
    std::map<int, int> m;
    for(p e: s){
        m[e.second] = e.first; 
    }
    // put back in the set
    s.clear();
    for(p e: m){
        s.emplace(e.second, e.first);
    }
    // print out
    for(p e: s){
        std::cout << e.first << ' ' << e.second <<'\n';
    }
}

【讨论】:

    【解决方案3】:

    Live Coliru Demo

    #include <boost/multi_index_container.hpp>
    #include <boost/multi_index/ordered_index.hpp>
    #include <boost/multi_index/key.hpp>
    #include <utility>
    
    using namespace boost::multi_index;
    using int_pair=std::pair<int,int>;
    using container=multi_index_container<
      int_pair,
      indexed_by<
        ordered_non_unique<key<&int_pair::first>>,
        ordered_unique<key<&int_pair::second>>
      >
    >;
    
    #include <iostream>
    
    int main()
    {
      container c={{1,5},{5,2},{3,3},{2,4},{4,3}};
      
      for(const auto& p:c)std::cout<<p.first<<" "<<p.second<<"\n";
    }
    

    输出

    1 5
    2 4
    3 3
    5 2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-29
      • 1970-01-01
      • 1970-01-01
      • 2011-02-18
      • 1970-01-01
      • 2014-03-03
      • 1970-01-01
      相关资源
      最近更新 更多