1. 程式人生 > 實用技巧 >優先佇列 priority_queue

優先佇列 priority_queue

用堆結構實現的優先佇列priority_queue

優先佇列具有佇列的所有特性,在這基礎上添加了內部的一個排序,本質是堆實現的

引數模版
//priority_queue< type, container, function >

這三個引數,後面兩個可以省略,第一個不可以。
其中:

  • type:資料型別;
  • container:實現優先佇列的底層容器;
  • function:元素之間的比較方式;

對於container,要求必須是陣列形式實現的容器,例如vector、deque,而不能使list。
在STL中,預設情況下(不加後面兩個引數)是以vector為容器,以 operator<

為比較方式,所以在只使用第一個引數時,優先佇列預設是一個最大堆,每次輸出的堆頂元素是此時堆中的最大元素。

成員函式

假設type型別為int,則:

  • bool empty() const
    返回值為true,說明佇列為空;
  • int size() const
    返回優先佇列中元素的數量;
  • void pop()
    刪除佇列頂部的元素,也即根節點
  • int top()
    返回佇列中的頂部元素,但不刪除該元素;
  • void push(int arg)
    將元素arg插入到佇列之中;
1.當使用基本資料型別(如int)時

需要注意的是,如果使用less<int>greater<int>,需要標頭檔案:

  • #include <functional>
//預設大頂堆
priority_queue<int> a;
//升序佇列,小頂堆
priority_queue <int,vector<int>,greater<int> > q;
//降序佇列
priority_queue <int,vector<int>,less<int> >q;

//greater和less是std實現的兩個仿函式(就是使一個類的使用看上去像一個函式。其實現就是類中實現一個operator(),這個類就有了類似函式的行為,就是一個仿函式類了)
2.對於自定義型別,需要對運算子過載、重寫仿函式
//方法1(仍然利用預設funtional,但是需要過載其中的 <運算子 來實現對自定義型別的比較)(這種方法只能使用帶一個引數的模版宣告物件,不能使用less<tmp1>和greater<tmp1>,)
struct tmp1 //運算子過載<
{
    int x;
    tmp1(int a) {x = a;}
    bool operator<(const tmp1& a) const
    {
        return x < a.x; //大頂堆
    }
};

tmp1 a(1);
tmp1 b(2);
tmp1 c(3);
priority_queue<tmp1> d;//priority_queue<tmp1,vector<tmp1>
d.push(b);
d.push(c);
d.push(a);
//此時d.top == c(3)

//方法2(可以使用帶三個引數的模版宣告物件了)
struct tmp1 //運算子過載<
{
    int x;
    tmp1(int a) {x = a;}
    bool operator<(const tmp1& a) const
    {
        return x < a.x; //大頂堆
    }
};
struct cmp //重寫仿函式
{
    bool operator() (tmp1 a, tmp1 b) 
    {
        return a.x < b.x; //大頂堆
    }
};
priority_queue<rmp1,vector<tmp1>,tmp2> f;


參考文章:
https://blog.csdn.net/lym940928/article/details/89635690