优先队列:(来自一位大佬的)
首先,你需要
#include<queue>
using namespace std;
这两个头文件。
其次,一个优先队列声明的基本格式是:
priority_queue<结构类型> 队列名;
比如:
priority_queue <int> i;
priority_queue <double> d;
不过,我们最为常用的是这几种:
priority_queue <node> q;
//node是一个结构体
//结构体里重载了‘<’小于符号
priority_queue <int,vector<int>,greater<int> > q;
//不需要#include<vector>头文件
//注意后面两个“>”不要写在一起,“>>”是右移运算符
priority_queue <int,vector<int>,less<int> >q;
我们将在下文来讲讲这几种声明方式的不同。
优先队列的基本操作
与队列的基本操作如出一辙。
以一个名为q的优先队列为例。
q.size();//返回q里元素个数
q.empty();//返回q是否为空,空则返回1,否则返回0
q.push(k);//在q的末尾插入k
q.pop();//删掉q的第一个元素
q.top();//返回q的第一个元素
q.back();//返回q的末尾元素
优先队列的特性
上文已经说过了,自动排序。
怎么个排法呢?
在这里介绍一下:
默认的优先队列(非结构体结构)
priority_queue <int> q;
这样的优先队列是怎样的?让我们写程序验证一下。
#include<cstdio>
#include<queue>
using namespace std;
priority_queue <int> q;
int main()
{
q.push(10),q.push(8),q.push(12),q.push(14),q.push(6);
while(!q.empty())
printf("%d ",q.top()),q.pop();
}
程序大意就是在这个优先队列里依次插入10、8、12、14、6,再输出。
结果是什么呢? 14 12 10 8 6
也就是说,它是按从大到小排序的!