有没有一种方法可以根据用户对配对向量进行排序?

问题描述 投票:0回答:1

我想按照对的第二个按降序排序,但是当第二个对两个或多个元素的值相同时,将基于对中的第一个进行排序

我已经根据秒以降序实现了排序,但是具有相同的秒值,它只是保持其顺序,我想根据降序对第一类似的元素进行排序。'''

#include<bits/stdc++.h>
using namespace std;
bool sortbysecdesc(const pair<long long int,long long int> &a,const pair<long long int,long long int> &b){
        return a.second>b.second;
}
int main()
{
    vector<pair<long long int,long long int> >v;
    long long int n,i,temp,s;
    cin>>n;
    for(i=0;i<n;i++){
        cin>>s;
        cin>>temp;
        v.push_back(make_pair(s,temp));
    }
    cout<<"\n\n\n\n";
    sort(v.begin(),v.end(),sortbysecdesc);
    for(i=0;i<v.size();i++){
        cout<<v[i].first<<" "<<v[i].second<<"\n";
    }
    return 0;
}

'''

Input :
999 100
1001 100
1002 100
1003 100
1004 50
1005 -50
1006 -50
1007 50
Expected Output :
1003 100
1002 100
1001 100
999 100
1007 50
1004 50
1006 -50
1005 -50
sorting c++14 stdvector std-pair
1个回答
1
投票
bool sortbysecdesc(const pair<long long int,long long int> &a,const pair<long long int,long long int> &b){
        if (a.second == b.second) {
            return a.first > b.first
        }
        return a.second > b.second;
}

0
投票

可能是这样:

bool MyFancySort(const pair<long long int,long long int>& a,
                 const pair<long long int,long long int>& b) {
  return std::make_tuple(-a.second, a.first) < std::make_tuple(-b.second, b.first);
}

sort(v.begin(), v.end(), MyFancySort);

EDIT:最初还不清楚您是否也希望按降序排列第一个组件。在这种情况下:

bool MyFancySort(const pair<long long int,long long int>& a,
                 const pair<long long int,long long int>& b) {
  return std::make_tuple(a.second, a.first) > std::make_tuple(b.second, b.first);
}
© www.soinside.com 2019 - 2024. All rights reserved.