int main()
{
priority_queue<int> qi;
for( int i = 0 ; i < 10 ; i ++ )
qi.push(i);
for( int i = 0 ; i < 10 ; i ++ ){
int t = qi.top();
cout << t << " ";
qi.pop();
}
cout << endl;
return 0;
}
默认最大堆 队首一定是最大的 但是队首的下一位不一定是次大的 因此在执行pop()的时候会执行shift_up 即弹出队首 经过调整把次大的当做队首 以此循环 最终会输出降序。
int tmp[100];
struct cmp1{
bool operator()( int x , int y ){
return x > y; //小的优先级高
}
};
struct cmp2{
bool operator()( int x , int y ){
return tmp[x] > tmp[y];
}
};
struct node{
int x , y;
friend bool operator < ( node a , node b ){
return a.x > b.x; // x小的优先级高
}
};
priority_queue<int> q1;
priority_queue<int,vector<int>,cmp1 > q2;
priority_queue<int,vector<int>,cmp2 > q3;
priority_queue<node> q4;
int main()
{
int n;
node a;
while( cin >> n ){
for( int i = 0 ; i < n ; i ++ ){
cin >> a.x >> a.y;
q4.push(a);
}
while( !q4.empty()){
cout << q4.top().x << " " << q4.top().y << endl;
q4.pop();
}
}
return 0;
}
其中pop()的定义:
void pop()
{ // erase highest-priority element
pop_heap(c.begin(), c.end(), comp);
c.pop_back();
}
comp是重载<运算符的 在这里按照x的值构成最小堆 但是不理解运行机制是怎样的
/*********************************************************分割线****************************************************************************/
#include "pch.h"
#include <iostream>
#include <queue>
using namespace std;
int a[] = { 3,5,2,4,7,9,5,2,0,10 };
int main()
{
int n = 10;
priority_queue<int> q1;
for (int i = 0; i < n; i++)
q1.push(a[i]);
for (; q1.size() > 0;) {
cout << q1.top() << " ";
q1.pop();
}
return 0;
}
默认最大堆 即最大的元素优先出队
https://www.cnblogs.com/xzxl/p/7266404.html