C++ Queue 库 - swap() 函数
描述
C++ 函数 std::priority_queue::swap() 将 priority_queue 的内容与另一个 priority_queue 的内容交换。
声明
以下是 std::priority_queue::swap() 函数形式 std::queue 头的声明。
C++11
void swap (priority_queue& x) noexcept;
参数
x − 另一个相同类型的 priority_queue 对象。
返回值
None.
异常
此成员函数从不抛出异常。
时间复杂度
常数,即 O(1)
示例
下面的例子展示了 std::priority_queue::swap() 函数的用法。
#include <iostream>
#include <queue>
using namespace std;
int main(void) {
auto it1 = {3, 1, 5, 2, 4};
auto it2 = {5, 2, 4};
priority_queue<int> q1(less<int>(), it1);
priority_queue<int> q2(less<int>(), it2);
q1.swap(q2);
cout << "Contents of q1 after swap operation" << endl;
while (!q1.empty()) {
cout << q1.top() << endl;
q1.pop();
}
cout << "Contents of q2 after swap operation" << endl;
while (!q2.empty()) {
cout << q2.top() << endl;
q2.pop();
}
return 0;
}
让我们编译并运行上面的程序,这将产生以下结果 −
Contents of q1 after swap operation 5 4 2 Contents of q2 after swap operation 5 4 3 2 1

