优先队列

转 https://blog.csdn.net/qq_19656301/article/details/82490601

优先队列可以实现自动排序功能

优先队列的头文件&&声明

一个优先队列声明的基本格式是: 

priority_queue<结构类型> 队列名; 
比如:

priority_queue <int> i;
priority_queue <double> d; 

不过,我们最为常用的是这几种:

priority_queue <node> q; //node是一个结构体,结构体里重载了小于符号
priority_queue <int,vector<int>,greater<int> > q; //注意后面两个 '>'不要写一起
priority_queue <int,vector<int>,less<int> > q;


优先队列的基本操作和队列的一样
q.size();//返回q里元素个数
q.empty();//返回q是否为空,空则返回1,否则返回0
q.push(k);//在q的末尾插入k
q.pop();//删掉q的第一个元素
q.top();//返回q的第一个元素
q.back();//返回q的末尾元素

默认的优先队列(非结构体结构)

#include<bits/stdc++.h>
using namespace std;
int main(){
    priority_queue <int> q;
    q.push(10),q.push(8),q.push(12),q.push(14),q.push(6);
    while(!q.empty())
    cout<<q.top()<<" ",q.pop();
    return 0; 
}

运行结果:

14 12 10 8 6

可以看出是从大到小排序的

默认的优先队列(结构体,重载小于)

#include<bits/stdc++.h>
using namespace std;
struct node{
    int x,y;
    bool operator<(const node & a) const{
    return x<a.x;
    }
}k;
priority_queue <node> q;
int main(){
    k.x=10,k.y=100;  q.push(k);
    k.x=12,k.y=60;   q.push(k);
    k.x=14,k.y=40;   q.push(k);
    k.x=6,k.y=80;    q.push(k);
    k.x=8,k.y=20;    q.push(k);
    while(!q.empty())
    {
        node m=q.top(); 
        q.pop();
        cout<<"("<<m.x<<","<<m.y<<")";
    }
}

程序大意就是插入(10,100),(12,60),(14,40),(6,20),(8,20)这五个node。 
再来看看它的输出:

(14,40)(12,60)(10,100)(8,20)(6,80)

它也是从大到小排序的。

less和greater优先队列

#include<bits/stdc++.h>
using namespace std;
priority_queue <int,vector<int>,less<int> > p;
priority_queue <int,vector<int>,greater<int> > q;
int a[5]={10,12,14,6,8};
int main()
{
    for(int i=0;i<5;i++){
        p.push(a[i]);
        q.push(a[i]);
    }
    cout<<"less<int>:";
    while(!p.empty()){
        cout<<p.top()<<" ";
        p.pop(); 
    }
    cout<<endl;    
    cout<<"greater<int>:";
    while(!q.empty()){
        cout<<q.top()<<" ";
        q.pop();    
    }
    return 0;
}

输出结果:

less<int>:14 12 10 8 6
greater<int>:6 8 10 12 14

所以,less是从大到小的,greater是从小到大的。


原文地址:https://www.cnblogs.com/wushengyang/p/10923188.html