優先佇列詳解

2021-09-02 17:12:59 字數 1029 閱讀 6442

優先佇列具有佇列的所有特性,包括基本操作,只是在這基礎上新增了內部的乙個排序,它本質是乙個堆實現的 

定義:priority_queue

type 就是資料型別,container 就是容器型別(container必須是用陣列實現的容器,比如vector,deque等等,但不能用 list。stl裡面預設用的是vector),functional 就是比較的方式,當需要用自定義的資料型別時才需要傳入這三個引數,使用基本資料型別時,只需要傳入資料型別,預設是大頂堆 

//公升序佇列

priority_queue ,greater> q;

//降序佇列

priority_queue ,less>q;

//greater和less是std實現的兩個仿函式(就是使乙個類的使用看上去像乙個函式。

其實現就是類中實現乙個operator(),這個類就有了類似函式的行為,

就是乙個仿函式類了)

列子:

#include#include using namespace std;

int main()

while (!a.empty())

}/*輸出

2 51 3

1 2*/

3.對於自定義型別

#include #include using namespace std;

//方法1

struct tmp1 //運算子過載<

bool operator<(const tmp1& a) const

};//方法2

struct tmp2 //重寫仿函式

};int main()

cout << endl;

priority_queue, tmp2> f;

f.push(c);

f.push(b);

f.push(a);

while (!f.empty())

}/*3213

21*/

優先佇列詳解

在優先佇列中,優先順序高的元素優先出列,複雜度為log n empty true if the priority queue has no elements popremoves the top element of a priority queue push adds an element to ...

STL優先佇列詳解

優先佇列是一種抽象資料型別 abstract date type,adt 行為和佇列類似,但是先出隊的元素不是先進佇列的元素,而是佇列中優先順序最高的元素。stl的優先佇列定義在標頭檔案和 佇列一樣 用 priority queuepq 來宣告 最基本的用法 定義 priority queuepq ...

優先佇列priority queue詳解

include using namespace std 比如 priority queue i priority queue d priority queue q node是乙個結構體 結構體裡過載了 小於符號 priority queue greater q 不需要 include標頭檔案 注意後...