C++ STL 中的棧 push() 和 pop()


在本文中,我們將討論 C++ STL 中 stack::push() 和 stack::pop() 函式的工作原理、語法和示例。

什麼是 C++ STL 中的棧?

棧是一種資料結構,它以 LIFO(後進先出)的方式儲存資料,我們從最後一個插入元素的頂部進行插入和刪除操作。就像一疊盤子,如果我們想將一個新的盤子推入棧中,我們將其插入頂部;如果我們想從棧中移除一個盤子,我們也從頂部將其移除。

什麼是 stack::push()?

stack::push() 函式是 C++ STL 中的一個內建函式,它在 <stack> 標頭檔案中定義。push() 用於將元素推入或插入到棧容器的頂部。新元素的內容被複制並初始化。

語法

stack_name.push(value_type& val);

引數

該函式接受以下引數:

  • val - 我們想要推入的值

返回值

此函式不返回任何值。

輸入

std::stack<int> stack1;
stack1.push(1);
stack1.push(2);
stack1.push(3);

輸出

3 2 1

示例

線上演示

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

什麼是 stack::pop()?

stack::pop() 函式是 C++ STL 中的一個內建函式,它在 <stack> 標頭檔案中定義。pop() 用於彈出或從棧容器的頂部移除一個元素。頂部的內容被移除,容器的大小減少 1。

語法

stack_name.pop();

引數

該函式不接受任何引數。

返回值

此函式不返回任何值。

輸入

std::stack<int> stack1;
stack1.push(1);
stack1.push(2);
stack1.push(3);
stack1.pop();

輸出

2 1

示例

線上演示

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

更新於: 2020-04-22

7K+ 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告