【问题标题】:Sorting a vector of pairs <int,int> [closed]对 <int,int> 对的向量进行排序 [关闭]
【发布时间】:2014-05-10 11:59:35
【问题描述】:

当对是 incr&lt;int,int&gt;时,如何使用 STL 中的 std::sort() 对向量进行降序排序?它应该首先对第一个元素进行排序,然后对第二个元素进行排序。

【问题讨论】:

  • 试一试,你会看到它是否有效

标签: c++ sorting stl


【解决方案1】:

operator&lt;pair&lt;int,int&gt; 进行了重载,因此您可以像对任何其他向量一样对成对向量进行排序。如果您需要降序排列,您有两个选择 - 排序然后调用 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;
}

【讨论】:

  • 感谢回复。我知道排序功能是在“nlogn”时间内工作的。排序然后反转不会需要更长的时间吗?
  • 逆向是线性的,因此排序然后逆向具有O(n*log(n) + n) = O(n * log(n))的复杂性,因为n*log(n)的增长速度比n快。
  • 这正是我想要的。谢谢。
【解决方案2】:

使用这个,

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;
    }
}

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

【讨论】:

  • 这是一个相当复杂的解决方案,考虑到greater&lt;pair&lt;int,int&gt; &gt; 会起作用。
猜你喜欢
  • 1970-01-01
  • 2020-08-03
  • 1970-01-01
  • 1970-01-01
  • 2017-03-15
  • 2019-10-11
  • 2017-12-05
  • 1970-01-01
  • 2015-09-03
相关资源
最近更新 更多