C++ 堆疊庫 - stack() 函式



描述

C++ 建構函式 **std::stack::stack()** 建立堆疊容器併為堆疊元素分配引數的副本。ctnr如果ctnr未提供引數,則構造一個包含零個元素的空堆疊。

宣告

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

C++98

explicit stack (const container_type& ctnr = container_type());

C++11

explicit stack (const container_type& ctnr);

引數

**ctnr** − 容器型別,它是類模板的第二個引數。

返回值

建構函式永不返回值。

異常

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

時間複雜度

線性,即 O(n)

示例

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

#include <iostream>
#include <stack>
#include <vector>

using namespace std;

int main(void) {   
   stack<int> s1;
   vector<int> v = {1, 2, 3, 4, 5};
   stack<int, vector<int>> s2(v);

   cout << "Size of stack s1 = " << s1.size() << endl;

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

   return 0;
}

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

Size of stack s1 = 0
Contents of stack s2
5
4
3
2
1
stack.htm
廣告