【问题标题】:How to sort on the basis of 2nd element if there is a tie on first in vector of tuples如果元组向量中的第一个元素存在平局,如何根据第二个元素进行排序
【发布时间】:2016-06-22 00:53:18
【问题描述】:
#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;
}
  • 我希望根据元组的第一个元素对向量进行排序,但只有当存在平局时,必须选择元组的第二个元素中最小的一个,才能对具有相同第一个值的元素进行排序.
  • 还指定应该做什么,如果在平局时应该根据元组的第二个元素(而不是第一个)的更大元素来维持顺序。

【问题讨论】:

    标签: c++11 stdvector stdtuple


    【解决方案1】:

    作为第三个参数的自定义函数完美地解决了我的问题。

    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.
    

    【讨论】:

      猜你喜欢
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      • 2021-09-25
      • 2011-05-21
      • 2010-09-21
      • 1970-01-01
      • 1970-01-01
      • 2015-06-16
      相关资源
      最近更新 更多