c++ - 如何对包含 pair<int,int> 元素的 vector 进行排序?根据比较功能进行排序

标签 c++ sorting vector stl

typedef pair<int,int>ii;
vector<ii>vii;

sort(vii.begin(),vii.end(),comp);

 ii comp(ii a,ii b){
   if(a.first>b.first)
   return a;
   else if(a.first==b.first){
    if(a.second>b.second)
    return a;
    else
    return b;
   }
   else{
    return b;
   }
 }

//这样会抛出一个编译错误。您能否指导如何根据//比较函数中给出的条件对该 vector 进行排序。

最佳答案

您可能想按字典顺序对它们进行升序排序。你可以这样做:

std::sort(vii.begin(), vii.end(), std::greater<std::pair<int,int>>());

比较仿函数是一个二元谓词,必须返回一个 bool 值,并实现strict weak ordering。 . std::greater<std::pair<int,int>>为你做。

关于c++ - 如何对包含 pair<int,int> 元素的 vector 进行排序?根据比较功能进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19795341/

相关文章:

c++ - 传递多维数组给出和错误

c++ - QDateTimeAxis (QtCharts) 中的错误值

Matlab:索引向量值与固定值相同

c++ - 返回私有(private) vector

c++ - vector 元素似乎没有连续存储

C++ 字符串解析到 Delphi

C++循环引用问题

javascript - 如何使用排序将 undefined 或 null 推到数组的后面?

c++ - 如何使用 sort 对类中的 vector 进行排序

java - 按度数对多项式链表进行排序