C++ Stack::pop() 函式



C++ 函式std::stack::pop() 從堆疊頂部移除一個元素,有效地將其大小減一。

pop() 函式不接受任何引數並返回 void。此外,重要的是要確保不能在空堆疊上呼叫 pop() 函式,如果嘗試這樣做,它將丟擲異常。

pop() 函式作為 LIFO(後進先出)順序中的刪除操作。這意味著最後插入堆疊的元素是第一個被移除的元素,而第一個插入堆疊的元素是最後一個被移除的元素。

pop() 函式的複雜度為 O(1),這意味著無論堆疊的大小如何,它的執行時間都是恆定的。

語法

以下是 std::stack::pop() 函式的語法:

void stack_name.pop();

引數

此函式不接受任何引數。

返回值

此函式沒有返回值。

示例 1

以下示例顯示了 std::stack::pop() 函式的使用方法。這裡我們建立一個空的整數堆疊,並使用 emplace() 函式向其中插入五個元素。然後,我們使用 top() 和 pop() 函式分別以 LIFO 順序檢索和移除元素,直到堆疊變空。

#include <iostream>
#include <stack>
using namespace std;

int main(void) {
   stack<int> s;
   for (int i = 0; i < 5; ++i)
      s.emplace(i + 1);
   while (!s.empty()) {
      cout << s.top() << endl;
      s.pop();
   }
   return 0;
}

輸出

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

5
4
3
2
1

示例 2

在這裡,我們嘗試按 1 到 6 的數字順序將元素插入堆疊。然後,我們使用 pop() 函式逐一移除元素並計算元素的乘積,直到堆疊變空。最後,我們使用 size() 函式在 while 迴圈的每次迭代中檢索堆疊的大小,並在堆疊變空後列印乘積。

#include <iostream>
#include <stack>
using namespace std;

int main(){
   stack<int> stck;
   int Product = 1;
   stck.push(1);
   stck.push(2);
   stck.push(3);
   stck.push(4);
   stck.push(5);
   stck.push(6);
   while (!stck.empty()){
      Product = Product * stck.top();
      cout<<"\nsize of stack is: "<<stck.size();
      stck.pop();
   }
   cout<<"\nThe product of the elements is: "<<Product;
   return 0;
}

輸出

如果我們執行上述程式碼,它將生成以下輸出:

size of stack is: 6
size of stack is: 5
size of stack is: 4
size of stack is: 3
size of stack is: 2
size of stack is: 1
The product of the elements is: 720

示例 3

現在,我們使用名稱 s1 建立一個空的字元資料型別的堆疊,並按順序將字元 't'、'r'、'u'、'c' 和 'k' 插入堆疊。然後,我們分別使用 top() 和 pop() 函式從堆疊中檢索和移除元素,直到堆疊變空。

#include <iostream>
#include <stack>
using namespace std;

int main(void) {
   stack <char> s1;
   s1.push('t');
   s1.push('r');
   s1.push('u');
   s1.push('c');
   s1.push('k');
   cout << "Contents of stack s1" << endl;
   while (!s1.empty()) {
      cout << s1.top() << endl;
      s1.pop();
   }
   return 0;
}

輸出

上述程式碼的輸出如下:

Contents of stack s1
k
c
u
r
t

示例 4

在下面的示例中,我們建立一個浮點數資料型別的堆疊,然後向其中插入 6 個元素。然後我們移除前 3 個元素,然後檢索並移除剩餘元素,直到堆疊變空。

#include <iostream>
#include <stack>
using namespace std;

int main() {
   stack<float> s;
   s.push(87.45f);
   s.push(43.76f);
   s.push(365.43f);
   s.push(32.67f);
   s.push(79.6f);
   s.push(645.76f);
   s.pop();
   s.pop();
   s.pop();
   while (!s.empty()) {
      cout << s.top() << endl;
      s.pop();
   }
   return 0;
}

輸出

以下是上述程式碼的輸出:

365.43
43.76
87.45
廣告
© . All rights reserved.