优先队列——Priority_Queue 详解

一、入门介绍

1、 优先队列是一种特殊的队列,这种队列会自动的把队列里的数排序(默认从大到小,使用“<”判断),而且还可以把数按照特定的方法排列!(包括结构体和重载"<")
2、 优先队列的头文件,需要包括:

#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; // 从小到大排序(数组)
         
priority_queue <int,vector<int>,less<int> >q;   // 从大到小排序
 
         //不需要#include<vector>头文件
         //注意后面两个“>”不要写在一起,“>>”是右移运算符

二、优先队列的基本操作:

1、以一个名为q的优先队列为例:

q.size();     //返回q里元素个数
q.empty();    //返回q是否为空,空则返回1,否则返回0
q.push(k);    //在q的末尾插入k
q.pop();     //删掉q的第一个元素
q.top();     //返回q的第一个元素
q.back();    //返回q的末尾元素

2、优先队列的特性
自动排序。
怎么个排法呢? 在这里介绍一下:
(1)、默认的优先队列(非结构体结构)

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
也就是说,它是按从大到小排序的!
(2)、默认的优先队列(结构体,重载小于)
        先看看这个结构体是什么。

struct node
{
    int x,y;
    bool operator < (const node & a) const
    {
        return x<a.x;
    }
};

这个node结构体有两个成员,x和y,它的小于规则是x小者小。
再来看看验证程序:

#include<cstdio>
#include<queue>
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();
        printf("(%d,%d) ",m.x,m.y);
    }
}

(3)、less和greater优先队列(多使用这一个)
还是以int为例,先来声明:

priority_queue <int,vector<int>,less<int> > p;     // 数组从大到小排序
 
priority_queue <int,vector<int>,greater<int> > q;  // 从小到大排序

CODE:

#include<cstdio>
#include<queue>
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]);
 
    printf("less<int>:")
    while(!p.empty())
        printf("%d ",p.top()),p.pop();  
 
    pritntf("\ngreater<int>:")
    while(!q.empty())
        printf("%d ",q.top()),q.pop();
}

结果:

less:14 12 10 8 6
greater:6 8 10 12 14

所以,我们可以知道,less是从大到小,greater是从小到大。

猜你喜欢

转载自blog.csdn.net/qq_38984851/article/details/83059260