如果元组向量中的第一个元素有联系,如何根据第二个元素进行排序
How to sort on the basis of 2nd element if there is a tie on first in vector of tuples
#include <iostream>
#include <vector>
#include <algorithm>
#include <tuple>
using namespace std;
typedef long long ll;
vector < tuple <ll,ll,ll> > a;
int main()
{
ll t;
cin>>t;
ll id,z,p,l,c,s,newz;
while(t--)
{
cin>>id>>z>>p>>l>>c>>s;
newz=p*50+l*5+c*10+s*20;
a.push_back(make_tuple(z-newz,id,newz));
}
sort(a.begin(),a.end());
for(int i=0;i<5;i++)
{
tie(ignore,id,z)=a[i];
cout<<id<<" "<<z<<endl;
}
return 0;
}
- 我希望基于元组的第一个元素对向量进行排序,但只有当存在平局时,才必须选择元组的第二个元素中最小的元素来对具有相同元素的元素进行排序第一个值。
- 还指定应该做什么,如果在平局时应该根据元组的第二个元素(而不是第一个)的更大元素来维持顺序。
作为第三个参数的自定义函数完美地解决了我的问题。
bool cmp( tuple <ll,ll,ll> const &s, tuple <ll,ll,ll> const &r)
{
if(get<0>(s)==get<0>(r))
{
return (get<1>(s))>(get<1>(r));
}
else
return (get<0>(s))<(get<0>(r));
}
sort(a.begin(),a.end(),cmp);// Call to sort will change like this.
#include <iostream>
#include <vector>
#include <algorithm>
#include <tuple>
using namespace std;
typedef long long ll;
vector < tuple <ll,ll,ll> > a;
int main()
{
ll t;
cin>>t;
ll id,z,p,l,c,s,newz;
while(t--)
{
cin>>id>>z>>p>>l>>c>>s;
newz=p*50+l*5+c*10+s*20;
a.push_back(make_tuple(z-newz,id,newz));
}
sort(a.begin(),a.end());
for(int i=0;i<5;i++)
{
tie(ignore,id,z)=a[i];
cout<<id<<" "<<z<<endl;
}
return 0;
}
- 我希望基于元组的第一个元素对向量进行排序,但只有当存在平局时,才必须选择元组的第二个元素中最小的元素来对具有相同元素的元素进行排序第一个值。
- 还指定应该做什么,如果在平局时应该根据元组的第二个元素(而不是第一个)的更大元素来维持顺序。
作为第三个参数的自定义函数完美地解决了我的问题。
bool cmp( tuple <ll,ll,ll> const &s, tuple <ll,ll,ll> const &r)
{
if(get<0>(s)==get<0>(r))
{
return (get<1>(s))>(get<1>(r));
}
else
return (get<0>(s))<(get<0>(r));
}
sort(a.begin(),a.end(),cmp);// Call to sort will change like this.