版权声明:本文为博主原创文章,转载需标明原创地址 https://blog.csdn.net/qq_42321579/article/details/82938670
在优先队列中,元素被赋予优先级,当访问元素时,具有最高级优先级的元素先被访问。即优先队列具有最高级先出的行为特征。
优先队列在头文件#include <queue>中;
其声明格式为:priority_queue <int> ans;//声明一个名为ans的整形的优先队列
基本操作有:
empty( ) //判断一个队列是否为空
pop( ) //删除队顶元素
top( ) //返回优先队列的队顶元素
push( ) //加入一个元素
size( ) //返回优先队列中拥有的元素个数
优先队列的时间复杂度为O(logn),n为队列中元素的个数,其存取都需要时间。
在默认的优先队列中,优先级最高的先出队。默认的int类型的优先队列中先出队的为队列中较大的数。
第一种用法(默认从大到小排序):
priority_queue<int> q1;//默认从大到小排序,整数中元素大的优先级高
第二种用法(从小到大排序):
priority_queue<int,vector<int>,greater<int> >q1;
第二个参数为容器类型;
第三个参数为比较函数。
第三种用法:自定义排序规则
struct node
{
friend bool operator< (node n1, node n2)
{
return n1.priority < n2.priority;
}
int priority;
int value;
};
在该结构中,value为值,priority为优先级。
通过自定义operator<操作符来比较元素中的优先级。