C++ 中的优先队列
众所周知,队列数据结构是先进先出数据结构。队列也有一些变式。这些是双端队列和优先队列。
这里我们将看到队列的一种变式,即优先队列。在此结构中,队列中的每个元素都有自己的优先级。当我们将项目插入队列时,我们必须为其分配优先级值。它将首先删除优先级最高的元素。实现优先队列最简单的方法之一是使用堆数据结构。
让我们看一个用于优先队列 STL 的 C++ 代码。这里的优先级是根据值分配的。因此,值越高将被视为优先级最高的元素。
算法
insert(key, priority): Begin insert key at the end of the heap heapify the array based on the priority End delete(): Begin item := root element root := last element from array heapify the array to arrange based on priority return item End
示例
#include <iostream>
#include <queue>
using namespace std;
void dequeElements(priority_queue <int> que) {
priority_queue <int> q = que;
while(!q.empty()){
cout << q.top() << " ";
q.pop();
}
cout << endl;
}
int main() {
priority_queue <int> que;
que.push(10);
que.push(20);
que.push(30);
que.push(5);
que.push(1);
cout << "Currently que is holding : ";
dequeElements(que);
cout << "Size of queue : " << que.size() << endl;
cout << "Element at top position : " << que.top() << endl;
cout << "Delete from queue : ";
que.pop();
dequeElements(que);
cout << "Delete from queue : ";
que.pop();
dequeElements(que);
}输出
Currently que is holding : 30 20 10 5 1 Size of queue : 5 Element at top position : 30 Delete from queue : 20 10 5 1 Delete from queue : 10 5 1
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP