C++ 棧庫 - swap() 函式



描述

C++ 函式std::stack::swap() 交換兩個棧的內容,並在必要時修改棧的大小。

宣告

以下是來自 std::stack 標頭檔案的 std::stack::swap() 函式的宣告。

C++11

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

引數

  • stack1 - 第一個棧。

  • stack2 - 第二個棧。

返回值

異常

此函式從不丟擲異常。

時間複雜度

線性,即 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
stack.htm
廣告