Reputation: 21
I want to sort the vector of pair according to second of pair in descending order but when the second will be same value for two or more elements then sorting will be done in basis of first in pair
I had implemented the sorting in descending order according to second but with same values of second it simply maintain its order , I want to sort the similar elements of second according to first in descending order . '''
#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
Upvotes: 0
Views: 87
Reputation: 52471
Something like this, perhaps:
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: It was not originally clear that you wanted the first component in descending order, too. In that case:
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);
}
Upvotes: 1
Reputation: 89152
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;
}
Upvotes: 1