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

