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



描述

C++ 移動建構函式std::stack::stack()使用移動語義構造包含其他內容的堆疊。

宣告

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

C++11

template <class Alloc>
stack (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);

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

   stack<int> s2(move(s1));

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

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

   return 0;
}

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

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