C++ Stack 库 - swap() 函数
描述
C++ 函数 std::stack::swap() 交换两个大小的内容,并在必要时更改堆栈的大小。
声明
以下是 std::stack::swap() 函数形式 std::stack 头的声明。
C++11
void swap (stack& x) noexcept;
参数
x − 另一个相同类型的堆栈对象。
返回值
None
异常
此成员函数从不抛出异常。
时间复杂度
常数,即 O(1)
示例
以下示例显示了 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(100 + i);
s1.swap(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

