摘录:https://www.quora.com/How-do-I-sort-array-of-pair-int-int-in-C+±according-to-the-first-and-the-second-element
By default std::sort will sort based on pair::first and then pair::second
If you want the opposite write a comparator which is a function or function object that performs the operation of less than:
template<typename P> struct Cmp
{
bool operator()(const P &p1, const P &p2)
{
if(p1.second < p2.second) return true;
if(p1.second == p2.second) return p1.first < p2.first;
return false;
}
};
vector<pair<int, int> > vec;
// Fill vec with values
// Sort using the comparator
sort(vec.begin(), vec.end(), Cmp<pair<int, int> >());
In C++11 and above you can write that using a lambda like this:
typedef pair<int, int> P;
sort(vec.begin(), vec.end(), [](const P &p1, const P &p2) {
if(p1.second < p2.second) return true;
if(p1.second == p2.second) return p1.first < p2.first;
return false;});