C++ 棧庫 - operator= 函式



描述

C++ 函式std::stack::operator= 透過替換舊內容來為棧分配新內容。此方法根據需要修改棧的大小。

宣告

以下是來自 std::stack 標頭檔案的 std::stack::operator= 函式宣告。

C++11

stack<T, Container>& 
operator=( stack<T,Container>&& other );

引數

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

返回值

返回 this 指標。

異常

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

時間複雜度

線性,即 O(n)

示例

以下示例演示了 std::stack::operator= 函式的使用。

#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);

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

   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
廣告