举几个使用 priority_queue的代码例子
时间: 2023-07-08 07:26:51 浏览: 77
以下是三个使用 priority_queue 的代码例子:
1. 求一组数中的前 k 大元素
```c++
int main() {
int n = 10, k = 3;
vector<int> nums = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3};
priority_queue<int, vector<int>, greater<int>> pq;
for (int i = 0; i < n; i++) {
pq.push(nums[i]);
if (pq.size() > k) pq.pop();
}
while (!pq.empty()) {
cout << pq.top() << " ";
pq.pop();
}
return 0;
}
```
2. 最小的 k 个数
```c++
int main() {
int n = 10, k = 3;
vector<int> nums = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3};
priority_queue<int> pq;
for (int i = 0; i < n; i++) {
pq.push(nums[i]);
if (pq.size() > k) pq.pop();
}
while (!pq.empty()) {
cout << pq.top() << " ";
pq.pop();
}
return 0;
}
```
3. 利用优先队列实现堆排序
```c++
void heap_sort(vector<int>& nums) {
int n = nums.size();
priority_queue<int, vector<int>, greater<int>> pq;
for (int i = 0; i < n; i++) {
pq.push(nums[i]);
}
int i = 0;
while (!pq.empty()) {
nums[i++] = pq.top();
pq.pop();
}
}
```
阅读全文