優先隊列——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是從小到大。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章