目录

swap

描述 (Description)

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

声明 (Declaration)

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

C++11

template <class T, class Container>
void swap (stack<T,Container>& stack1, stack<T,Container>& stack2) noexcept;

参数 (Parameters)

  • stack1 - 第一个堆栈。

  • stack2 - 第二个堆栈。

返回值

没有

异常 (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(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
↑回到顶部↑
WIKI教程 @2018