#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int main() {
// 定义一个优先队列,默认是最大堆
priority_queue<int> maxHeap;
// 插入元素
maxHeap.push(10);
maxHeap.push(30);
maxHeap.push(20);
maxHeap.push(5);
maxHeap.push(1);
// 输出优先队列的大小
cout << "Size of the priority queue: " << maxHeap.size() << endl;
// 访问优先队列的顶部元素(最大值)
cout << "Top element is: " << maxHeap.top() << endl;
// 弹出顶部元素
maxHeap.pop();
// 再次访问顶部元素
cout << "Top element after pop is: " << maxHeap.top() << endl;
// 定义一个最小堆
priority_queue<int, vector<int>, greater<int>> minHeap;
// 插入元素
minHeap.push(10);
minHeap.push(30);
minHeap.push(20);
minHeap.push(5);
minHeap.push(1);
// 访问最小堆的顶部元素(最小值)
cout << "Top element of min heap is: " << minHeap.top() << endl;
return 0;
}
priority_queue<int>
默认是一个最大堆,即每次 top()
操作返回的是当前队列中的最大值。push()
方法向优先队列中插入元素。top()
方法可以访问优先队列中的最大值(对于最大堆)或最小值(对于最小堆),但不会移除它。pop()
方法移除并返回当前队列中的最大值(对于最大堆)或最小值(对于最小堆)。greater<int>
,可以将优先队列配置为最小堆。上一篇:俄罗斯方块c++代码
下一篇:c++ 判断文件是否存在
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站