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