目录

stack::swap

描述 (Description)

C ++函数std::stack::swap()交换两个大小的内容,并在必要时更改堆栈的大小。

声明 (Declaration)

以下是std :: stack :: swap()函数形式std :: stack标头的声明。

C++11

void swap (stack& x) noexcept;

参数 (Parameters)

x - 相同类型的另一个堆栈对象。

返回值

没有

异常 (Exceptions)

该成员函数从不抛出异常。

时间复杂

线性即O(n)

例子 (Example)

以下示例显示了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
↑回到顶部↑
WIKI教程 @2018