C++ Stack 库 - swap() 函数
描述
C++ 函数 std::stack::swap() 交换两个堆栈的内容并在必要时修改堆栈的大小。
声明
以下是 std::stack::swap() 函数形式 std::stack 头的声明。
C++11
template <class T, class Container> void swap (stack<T,Container>& stack1, stack<T,Container>& stack2) noexcept;
参数
stack1 − 第一个堆栈。
stack2 − 第二个堆栈。
返回值
None
异常
此函数从不抛出异常。
时间复杂度
线性,即 O(n)
示例
以下示例显示了 std::stack::swap() 函数的用法。
#include <iostream>
#include <stack>
using namespace std;
int main(void) {
stack<int> s1;
stack<int> s2;
for (int i = 0; i < 5; ++i)
s1.push(i + 1);
for (int i = 0; i < 3; ++i)
s2.push(i + 100);
swap(s1, s2);
cout << "Contents of stack s1 after swap operation." << endl;
while (!s1.empty()) {
cout << s1.top() << endl;
s1.pop();
}
cout << endl;
cout << "Contents of stack s2 after swap operation." << endl;
while (!s2.empty()) {
cout << s2.top() << endl;
s2.pop();
}
return 0;
}
让我们编译并运行上面的程序,这将产生以下结果 −
Contents of stack s1 after swap operation. 102 101 100 Contents of stack s2 after swap operation. 5 4 3 2 1

