C++ 標準模板庫 (STL) 中的優先順序佇列
優先順序佇列是一種抽象資料型別,用於儲存優先順序元素集合,支援基於優先順序插入和刪除元素,即隨時可以刪除優先順序最高的元素。與堆疊、佇列和列表等容器不同,優先順序佇列不會按照元素在容器中的位置對元素以線性方式儲存。優先順序佇列抽象資料型別根據元素的優先順序儲存元素。
優先順序佇列支援以下函式 −
Size() − 用於計算優先順序佇列的大小,即返回佇列中的元素數量。
Empty() − 如果優先順序佇列為空,則返回 true,否則返回 false
Insert(element) − 用於將新元素插入優先順序佇列
Min() − 返回關聯鍵值最小的元素,如果優先順序佇列為空,則顯示錯誤訊息。
removeMin()− 它刪除 min() 函式引用的元素。
下面是一張表格,顯示了操作對優先佇列的影響

Start Step 1-> Declare function to display the elements in a Priority Queue void display(priority_queue <int> Pq) declare and set priority_queue <int> que = Pq Loop While (!que.empty()) call que.top() call que.pop() End Step 2-> In main() Create object of priority_queue <int> Pq Call push() to insert element in a priority queue as Pq.push(1) Call display(Pq) Call to check the size of a priority queue Pq.size() Call to display the top element of a priority queue Pq.top() Call to remove the elements of a priority queue Pq.pop() Call display(Pq) Stop
示例
#include <iostream>
#include <queue>
using namespace std;
void display(priority_queue <int> Pq) {
priority_queue <int> que = Pq;
while (!que.empty()) {
cout << '\t' << que.top();
que.pop();
}
//cout << '\n';
}
int main () {
priority_queue <int> Pq;
Pq.push(1);
Pq.push(3);
Pq.push(5);
Pq.push(7);
Pq.push(9);
cout << "The priority queue is : ";
display(Pq);
cout << "\nPrioriy queue size using size() : " << Pq.size();
cout << "\nFirst element of priority queue using top(): " << Pq.top();
cout << "\nremoving element using pop() : ";
Pq.pop();
display(Pq);
return 0;
}輸出
The priority queue is : 9 7 5 3 1 Prioriy queue size using size() : 5 First element of priority queue using top(): 9 removing element using pop() : 7 5 3 1
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP