priority queue優先佇列

2021-10-25 16:59:28 字數 2935 閱讀 6661

合兩篇部落格,總結下c++ stl優先佇列(堆)的用法。

#include

priority_queuep; //預設大堆

普通的佇列是一種先進先出的資料結構,元素在佇列尾追加,而從佇列頭刪除(大家都是普通人,自覺排隊);在優先佇列中,元素被賦予優先順序。當訪問元素時,具有最高優先順序的元素最先刪除。優先佇列具有最高端先出 (first in, largest out)的行為特徵(階層劃分,出現了會員:青銅會員、**會員、鉑金會員...,不管來的先後,階層高低決定是否優先)。

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

和佇列基本操作相同:

定義:priority_queue

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

//公升序佇列,小頂堆

priority_queue ,greater> q;

//降序佇列,大頂堆

priority_queue ,less>q;

//greater和less是std實現的兩個仿函式(就是使乙個類的使用看上去像乙個函式。其實現就是類中實現乙個operator(),這個類就有了類似函式的行為,就是乙個仿函式類了)

1、基本型別優先佇列的例子:

#include#include using namespace std;

int main()

while (!a.empty())

cout << endl;

while (!c.empty())

cout << endl;

b.push("abc");

b.push("abcd");

b.push("cbd");

while (!b.empty())

cout << endl;

return 0;

}

4 3 2 1 0

0 1 2 3 4

cbd abcd abc

請按任意鍵繼續. . .

2、用pair做優先佇列元素的例子:規則:pair的比較,先比較第乙個元素,第乙個相等比較第二個。

#include #include #include using namespace std;

int main()

}

2 5

1 31 2

請按任意鍵繼續. . .

3、用自定義型別做優先佇列元素的例子:

#include #include using namespace std;

//方法1

struct tmp1 //運算子過載<

bool operator

};

//方法2

struct tmp2 //重寫仿函式

};

int main()

cout << endl;

//優先佇列元素型別為tmp1,儲存佇列用vector,用自定義的cmp函式tmp2比較元素大小

priority_queue, tmp2> f; //priority_queuef.push(b);

f.push(c);

f.push(a);

while (!f.empty())

}

321

321請按任意鍵繼續. . .

priority_queue

type為資料型別, container為儲存資料的容器,functional為元素比較方式。如果不寫後兩個引數,那麼容器預設用的是vector,比較方式預設用operator

#include#include#include//等價於c中的using namespace std;

struct node};

struct cmp};

int main(){

priority_queue, cmp>p;

for(int i=0; i<10; ++i)

p.push(node(rand(), rand()));

while(!p.empty()){

cout

stdlib.h提供以下型別:size_t, wchar_t, div_t, ldiv_t, lldiv_t

常量:null, exit_failure, exit_success, rand_max, mb_cur_max

函式:atof, atoi, atol, strtod, strtof, strtols, strtol, strtoll, strtoul, strtoull, rand, srand, calloc, free, malloc, realloc, abort, atexit, exit, getenv, system, bsearch, qsort, abs, div, labs, ldiv, llabs, tlldiv, mblen, mbtowc, wctomb, mbstowcs, wcstombs

參考:

priority queue 優先佇列)

佇列 先輸入先輸出 優先佇列使用方法 標頭檔案 include using namespace std 宣告方法 1.普通方法 priority queueq 下劃線不可漏,預設從大到小輸出隊 2.結構體宣告方式 struct node int x,y frinend bool operator n...

優先佇列 priority queue

優先佇列 是一種抽象資料型別,行為有些像佇列,但是他不是先進先出型佇列 先出優先佇列的元素是佇列中優先順序最高的元素。就像 急診病人插隊 優先佇列的標頭檔案也是 用 priority queuepq 來宣告。這個pq是乙個越小的整數優先順序越低的優先佇列。出隊元素不是先進隊的元素,出隊的方法由que...

優先佇列 PriorityQueue

import queue q queue.priorityqueue q.put 1 新增元素 q.get 刪除元素 python的優先佇列基於最小堆實現。heap 堆 是乙個除了底層節點外的完全填滿的二叉樹,底層可以不完全,左到右填充節點。而最小堆意味著,任一非終端節點的資料值均不大於其左子節點和...