C++中sort()和priority_queue自定义比较函数的区别

C++中sort()和priority_queue都能自定义比较函数,其中sort()自定义的比较函数比较好理解,priority_queue中自定义的比较函数的效果和sort()是相反的。代码如下

#include
using namespace std;
struct cmp{
   bool operator()(int a,int b){
       return a<b;
   }
};
int main(){
   vector<int> vec{2,5,4,7,1,6,17};
   sort(vec.begin(),vec.end(),cmp());
   cout<<"sort: ";
   for(int n:vec){
       cout<<n<<" ";
   }
   cout<<endl;
   //输出:sort: 1 2 4 5 6 7 17
   priority_queue<int,vector<int>,cmp> pq;
   for(int n:vec){
       pq.push(n);
   }
   cout<<"pq: ";
   while(!pq.empty()){
       cout<<pq.top()<<" ";
       pq.pop();
   }
   cout<<endl;
   //输出:pq: 17 7 6 5 4 2 1
   system("pause");
   return 0;
}

sort()和priority()都使用自定义的比较函数cmp,从输出的结果来看,经过sort后,向量中的元素升序排列,而priority_queue每次弹出的是最大的元素。

你可能感兴趣的:(C++,C++)