【发布时间】:2014-05-10 11:59:35
【问题描述】:
当对是 incr<int,int>时,如何使用 STL 中的 std::sort() 对向量进行降序排序?它应该首先对第一个元素进行排序,然后对第二个元素进行排序。
【问题讨论】:
-
试一试,你会看到它是否有效
当对是 incr<int,int>时,如何使用 STL 中的 std::sort() 对向量进行降序排序?它应该首先对第一个元素进行排序,然后对第二个元素进行排序。
【问题讨论】:
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;
}
【讨论】:
O(n*log(n) + n) = O(n * log(n))的复杂性,因为n*log(n)的增长速度比n快。
使用这个,
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<pair<int,int> > 会起作用。