知乎的这个答案很清晰https://www.zhihu.com/question/35736022
#include <iostream> #include <algorithm> #include <stdio.h> #include <cstring> #include <queue> using namespace std; struct NODE { int x,y; bool operator<(const NODE& p)const{ if(x==p.x) return y>p.y; return x<p.x; } }a[1005]; int main() { int len=0; a[len].x=1, a[len++].y=4; a[len].x=2, a[len++].y=3; a[len].x=2, a[len++].y=5; a[len].x=1, a[len++].y=3; sort(a,a+len); // 先按x升序排序 x相同时再按y降序排序 printf("sort: "); for(int i=0;i<len;i++) printf("%d %d ",a[i].x,a[i].y); printf(" "); priority_queue <NODE> q; // 先按x降序排序 x相同时再按y升序排序 q.push((NODE){1,4}); q.push((NODE){2,3}); q.push((NODE){2,5}); q.push((NODE){1,3}); printf("优先队列: "); while(!q.empty()) { printf("%d %d ",q.top().x,q.top().y); q.pop(); } printf(" "); return 0; }