对对向量进行排序 <int,int>

Sorting a vector of pairs <int,int>

本文关键字:int gt 向量 lt 排序      更新时间:2023-10-16

如何在STL中使用std::sort()在STL中使用incr <int,int>时按降序排序一对向量?它应该先对第一个元素排序,然后对第二个元素排序。

operator<对于pair<int,int>是重载的,因此您可以像任何其他向量一样对一对向量进行排序。如果您需要降序排序,您有两个选择—排序,然后调用std::reverse来反转结果,或者为排序提供谓词。

你也可以使用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;
}

use this,

template<class T>
struct sortFunctor: public unary_function<std::pair<int, int>, std::pair<int, int>>
{
    bool operator()(const std::pair<int, int>& First, const std::pair<int, int>& Second)
    {
        if(First.first < Second.first)
        {
            return false;
        }
        if(First.first == Second.first && First.second < Second.second)
        {
            return false;
        }
        return true;
    }
}

然后将此函子作为第三个形参传递给sort函数。