C ++中的优先级队列
众所周知,队列数据结构是先进先出数据结构。队列也有一些变化。这些是出队和优先级队列。
在这里,我们将看到队列的一种变化,即优先级队列。在这种结构中,队列中的每个元素都有其自己的优先级。当我们将项目插入队列时,我们必须为其分配优先级值。它将首先删除优先级最高的元素。要实现优先级队列,最简单的方法之一是使用堆数据结构。
让我们看一下优先队列STL的一个C++代码。在此,根据值分配优先级。因此,较高的值将被视为最高优先级元素。
算法
insert(key, priority):Begin insert key at the end of the heap heapify the array based on the priority Enddelete():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
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短