对对< int,int>的向量进行排序 [英] Sorting a vector of pairs <int,int>

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

问题描述

如何使用STL中的std :: sort()对成对的向量在降序排序时按降序排序?应该首先对第一个元素进行排序,然后对第二个元素进行排序.

How to sort a vector of pairs in descending order when the pair is incr<int,int>using the std::sort() in STL?It should sort first with respect to the first element and then the second.

推荐答案

对于pair<int,int>operator<已重载,因此您可以像其他任何向量一样对向量对进行排序.如果需要降序排列,则有两个选项-进行排序,然后调用std::reverse反转结果,或提供排序谓词.

The operator< is overloaded for pair<int,int> so you can sort a vector of pairs just like any other vector. If you need descending order, you have two options - either sort and then call std::reverse to reverse the result or provide predicate for the sorting.

您还可以使用std::greater:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<pair<int, int> > a;
    a.push_back(make_pair(1, 2));
    a.push_back(make_pair(2, 3));
    sort(a.begin(), a.end(), greater<pair<int,int> >());
    return 0;
}

这篇关于对对&lt; int,int&gt;的向量进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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