priority_queue的swap怎么用
时间: 2024-01-15 21:19:48 浏览: 111
c++优先队列(priority_queue)用法详解
5星 · 资源好评率100%
priority_queue的swap函数用于交换两个优先级队列的内容。下面是使用C++ STL中priority_queue的swap函数的示例代码:
```cpp
#include <iostream>
#include <queue>
int main() {
std::priority_queue<int> pq1;
std::priority_queue<int> pq2;
pq1.push(10);
pq1.push(20);
pq1.push(30);
pq2.push(100);
pq2.push(200);
pq2.push(300);
std::cout << "Before swap:" << std::endl;
std::cout << "pq1: ";
while (!pq1.empty()) {
std::cout << pq1.top() << " ";
pq1.pop();
}
std::cout << std::endl;
std::cout << "pq2: ";
while (!pq2.empty()) {
std::cout << pq2.top() << " ";
pq2.pop();
}
std::cout << std::endl;
pq1.swap(pq2);
std::cout << "After swap:" << std::endl;
std::cout << "pq1: "; while (!pq1.empty()) {
std::cout << pq1.top() << " ";
pq1.pop();
}
std::cout << std::endl;
std::cout << "pq2: ";
while (!pq2.empty()) {
std::cout << pq2.top() << " ";
pq2.pop();
}
std::cout << std::endl;
return 0;
}
```
输出结果为:
```
Before swap:
pq1: 30 20 10
pq2: 300 200 100
After swap:
pq1: 300 200 100
pq2: 30 20 10
```
阅读全文