C++ STL 中的 stack empty() 和 stack size()


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

什麼是 C++ STL 中的 Stack?

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

什麼是 stack::empty()?

stack::empty() 函式是 C++ STL 中的一個內建函式,它在 <stack> 標頭檔案中定義。empty() 用於檢查關聯的容器是否為空,並相應地返回 true 或 false。

該函式檢查容器是否為空,即容器的大小是否為 0。

語法

stack_name.empty();

引數

該函式不接受任何引數。

返回值

如果容器為空,則此函式返回 true,否則返回 false。

輸入 

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

輸出 

false

輸入 

std::stack<int> stack2;
stack2.empty();

輸出 

true

示例

 即時演示

#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();
      stck.pop();
   }
   cout<<"\nProduct of elements in stack are: "<<Product;
   return 0;
}

輸出

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

Product of elements in stack are: 720

什麼是 stack::size()?

stack::size() 函式是 C++ STL 中的一個內建函式,它在 <stack> 標頭檔案中定義。size() 用於檢查關聯容器的大小,並以整數值返回結果,該值是容器中元素的數量。

如果容器為空,則 size() 返回 0

語法

stack_name.size();

引數

該函式不接受任何引數。

返回值

此函式返回容器的大小

輸入 

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

輸出 

3

輸入

std::stack<int> stack2;
stack2.size();

輸出 

0

示例

 即時演示

#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);
   cout<<"size of stack is: "<<stck.size();
   while (stck.size()>0){
      Product = Product * stck.top();
      stck.pop();
   }
   cout<<"\nProduct of elements in stack are: "<<Product;
   return 0;
}

輸出

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

size of stack is: 6
Product of elements in stack are: 720

更新於: 2020-04-22

5K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告