C++ 棧庫 - stack() 函式



描述

C++ 複製建構函式 std::stack::stack() 使用另一個棧中存在的每個元素的副本構造一個棧。

宣告

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

C++11

template <class Alloc>
stack (const stack& x, const Alloc& alloc);

引數

  • x − 另一個相同型別的棧物件。

  • alloc − 分配器物件。

返回值

建構函式永不返回值。

異常

此成員函式永不丟擲異常。

時間複雜度

線性,即 O(n)

示例

以下示例演示了 std::stack::stack() 建構函式的使用。

#include <iostream>
#include <stack>

using namespace std;

int main(void) {   
   stack<int> s1;

   for (int i = 0; i < 5; ++i)
      s1.push(i + 1);

   stack<int> s2(s1);

   cout << "Contents of stack s2" << endl;
   while (!s2.empty()) {
      cout << s2.top() << endl;
      s2.pop();
   }

   return 0;
}

讓我們編譯並執行以上程式,這將產生以下結果:

Contents of stack s2
5
4
3
2
1
stack.htm
廣告