c++中的priority_queue即堆,默认是最大堆。
#include <iostream>
#include <vector>
#include <unordered_map>
#include <queue>
#include <string>
using namespace std;
struct cmp{
/*在左边(也就是队尾),优先级越低
* 默认使用less,小数在左边优先级越低
* 可选greater,大数在左边优先级越低
*
* */
bool operator ()(int a,int b){
return a<b;//小的放左边,即less
}
};
struct cmp2{
bool operator ()(int a,int b){
return a>b;//大的放左边,即greater
}
};
int main(){
priority_queue<int,vector<int>,cmp> pq;
pq.push(4);
pq.push(8);
pq.push(1);
pq.push(5);
while(!pq.empty()){
cout<<pq.top()<<" ";
pq.pop();
}
}
cmp返回8541,cmp2返回1458