priority_queue的用法

priority_queue本质是一个堆,默认为按照元素值的大小从大到小排序

1.简单的使用方法

//二叉树  默认为小根堆
#include<iostream>
#include<queue>
using namespace std;
int main()
{
    priority_queue<int>  pq;
    pq.push(1);
    cout<<pq.size()<<endl;
    while(pq.empty()){
        cout<<pq.top()<<" ";
        pq.pop();
    }
    cout<<endl;
} 
View Code

默认状态:

#include<iostream>
#include<queue>
using namespace std;
 
int main(){
    priority_queue<int> p;
    p.push(1);
    p.push(2);
    p.push(8);
    p.push(5);
    p.push(43);
    for(int i=0;i<5;i++){
        cout<<p.top()<<endl;
        p.pop();
    }
    return 0;
}
View Code

优先输出小数据:

priority_queue<int, vector<int>, greater<int> > p;

#include<iostream>
#include<queue>
using namespace std;
 
int main(){
    priority_queue<int, vector<int>, greater<int> >p;
    p.push(1);
    p.push(2);
    p.push(8);
    p.push(5);
    p.push(43);
    for(int i=0;i<5;i++){
        cout<<p.top()<<endl;
        p.pop();
    }
    return 0;
}
View Code

2.重载  “<”  定义优先级

#include<iostream>
#include<queue>
#include<cstdlib>
using namespace std;
struct Node{
    int x,y;
    Node(int a=0, int b=0):
        x(a), y(b) {}
};
 
struct cmp{
    bool operator()(Node a, Node b){
        if(a.x == b.x)    return a.y>b.y;
        return a.x>b.x;
    }
};
 
int main(){
    priority_queue<Node, vector<Node>, cmp>p;
    
    for(int i=0; i<10; ++i)
        p.push(Node(rand(), rand()));
        
    while(!p.empty()){
        cout<<p.top().x<<' '<<p.top().y<<endl;
        p.pop();
    }//while
    //getchar();
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/helloworld2019/p/10366298.html