【问题标题】:Sorting a vector with 2 pairs inside对内部有 2 对的向量进行排序
【发布时间】:2019-11-20 05:39:00
【问题描述】:

好吧,我有一个向量,对 >,我想知道他是如何进行排序的? with sort(v.begin(),v.end());

using namespace std;

int main(){
   int n; cin >> n;
   vector<pair<pair<int,int>, pair<int,int>>> v;
   for(int i=0;i<n;i++){
      long long x1,y1,x2,y2;
      cin>>x1>>y1>>x2>>y2;
      v.push_back(make_pair(make_pair(x1,y1),make_pair(x2,y2)));
   }   
   sort(v.begin(),v.end());
   for(auto& p : v){
      cout<<p.first.first<<" "<<p.first.second<<" "<<p.second.first<<" "<<p.second.second<<"\n";
  }
   return 0;
}

输入:

4   
5 19 8 17
5 15 15 5
0 20 20 0
8 10 10 8

输出:

0 20 20 0
5 15 15 5
5 19 8 17
8 10 10 8

【问题讨论】:

  • 从左到右排序:先是 x1,如果是 y1,如果是 x2,如果是 y2。

标签: c++ algorithm sorting vector std-pair


【解决方案1】:

对于std::pair 类,定义了运算符

template<class T1, class T2>
constexpr bool operator< (const pair<T1, T2>&, const pair<T1, T2>&);

按照以下方式进行操作

返回:x.first

例如对于std::pair&lt;std::pair&lt;int, int&gt;, std::pair&lt;int, int&gt;&gt;类型的两对

{ { 5, 19 }, { 8, 17 } }
  ^^^^^^^^^

{ { 5, 15 }, { 15, 5 } }
  ^^^^^^^^^

首先,{ 5, 19 }{ 5, 15 } 对使用相同的 operator &lt; 进行比较。

由于第二对小于第一对,因此第二对将在结果向量中位于第一对之前。

如果它们(第一对)彼此相等,例如

{ { 5, 15 }, { 8, 17 } }
  ^^^^^^^^^

{ { 5, 15 }, { 15, 5 } }
  ^^^^^^^^^

然后比较第二对。因为{ 8, 17 } 对小于{ 15, 5 },所以第一对小于第二对。

{ 8, 17 }{ 15, 5 } 对使用相同的模板 operator &lt; 进行比较。

【讨论】:

    【解决方案2】:

    std::pair 定义一个operator&lt;,如果包含的类型支持通过operator&lt; 进行比较,并且您使用的是int,因此默认提供。

    std::sort 使用此operator&lt; 对元素lexicographically 进行排序。

    如果您使用未定义 operator&lt; 的任意类型,则必须为 std::sort 提供自己的比较器

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-18
      • 1970-01-01
      • 1970-01-01
      • 2020-06-05
      • 1970-01-01
      • 2018-09-26
      • 1970-01-01
      相关资源
      最近更新 更多