向量<int,int>的比较器. [英] Comparator for vector&lt;pair&lt;int,int&gt;&gt;

查看:76
本文介绍了向量<int,int>的比较器.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

vector<pair<int,int> > v;
for(i=0;i<5;i++){
    cin>>b>>c;
    v.push_back(make_pair(b,c));
}
sort(v.begin(),v.end());

是否有可能为排序函数编写一个比较器,以便对 v [i] .first 进行递增排序,并对类似值的 v [i] .first 进行排序code>, v [i] .second 以降序排序?
像:-
i/p:

Is it possible to write a comparator for the sort function such that v[i].first is sorted in increasing order and for similar values of v[i].first, v[i].second is sorted in decreasing order?
like:-
i/p:

 13 10  
 44 15  
 13 15  
 13 99  
  6 45  

o/p:

 6 45  
 13 99  
 13 15  
 13 10  
 44 15 

推荐答案

当然,这很容易.

您需要做的就是编写一个具有以下签名的函数:

All you need to do is write a function with this signature:

bool f(std::pair<int, int> lhs, std::pair<int, int> rhs);

当且仅当 lhs<rhs

因此,根据您的标准,如果满足以下条件,则 lhs 小于 rhs :

So, by your criteria, lhs is smaller than rhs if:

  • lhs.first<rhs.first
  • lhs.first == rhs.first&&lhs.second>rhs.second

因此,基本上将它们放在一起,就可以得到:

So, basically just put those together, and you get:

bool mycomparer(std::pair<int, int> lhs, std::pair<int, int> rhs) {
    if (lhs.first < rhs.first) {
        return true;
    }
    else if (lhs.first == rhs.first && lhs.second > rhs.second) {
        return true;
    }
    else {
        return false;
    }
}

这可以写得更紧凑,但是我想保持它的简单和可读性以阐明要点.:)

This could be written much more compactly, but I wanted to keep it simple and readable to get the point across. :)

这篇关于向量<int,int>的比较器.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆