當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ Stack stack()用法及代碼示例


描述

C++複製構造函數std::stack::stack()構造一個堆棧,其中包含另一個堆棧中存在的每個元素的副本。

聲明

以下是 std::stack::stack() 構造函數形式 std::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

相關用法


注:本文由純淨天空篩選整理自 C++ Stack Library - stack() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。