C++ Stack::empty() 函式



C++ 的std::stack::empty()函式檢查堆疊是否為空(沒有元素)。大小為零的堆疊被認為是空堆疊。

此函式不接受任何引數,它是一個const成員函式。“const”關鍵字表示該函式不修改堆疊。如果堆疊為空,則返回布林true,否則返回false

當堆疊為空時,嘗試從中彈出元素將導致錯誤,因為沒有元素可刪除。因此,空堆疊通常用作涉及推送元素的操作的起點。

語法

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

bool stack_name.empty() const;

引數

此方法不接受任何引數。

返回值

如果堆疊為空,則返回 true,否則返回 false。

示例 1

以下示例顯示了 std::stack::empty() 函式的用法。首先,我們嘗試建立一個沒有元素的堆疊s,並使用 empty() 函式驗證它。然後,我們將元素 '1' 插入/壓入堆疊,並使用 empty() 函式確定此堆疊是否為空。

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

int main(void) {
   stack<int> s;
   if (s.empty()){
      cout << "Stack is empty." << endl;}
   else {
      cout << "Stack is not empty." << endl;} 
   s.emplace(1);
   if (!s.empty()){
      cout << "Stack is not empty." << endl;}
   else {
      cout << "Stack is empty." << endl;} 
   return 0;
}

輸出

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

Stack is empty.
Stack is not empty.

示例 2

在這裡,我們嘗試按順序將從 1 到 6 的數字插入堆疊。然後,我們使用 pop() 函式逐個刪除元素,並計算元素的乘積,直到堆疊為空。

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

int main() {
   stack<int> s;
   // initializing the variable Product with the value 1
   int Product = 1;
   for (int i=1;i<=6;i++)
   s.push(i);
   while (!s.empty()){
      // multiplying the topmost element of the stack with Product  
      Product = Product * s.top();
      s.pop();
   }
   cout << "The Product of elements is: " << Product << '\n';
   return 0;
}

輸出

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

The Product of elements is: 720

示例 3

在以下示例中,我們建立一個空堆疊s,然後將值 '10'、'20'、'30'、'3' 和 '0' 壓入其中。然後,我們使用 empty() 函式檢查堆疊是否為空,並根據結果列印結果。

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

int main() {
   stack<int> s;
   s.push(10);
   s.push(20);
   s.push(30);
   s.push(3);
   s.push(0);
   cout<<"stack s is empty: \n"<<s.empty()<<"\n"; 
   //empty stack  
   stack<int> s1;
   cout<<"stack s1 is empty: \n"<<s1.empty(); 
}

輸出

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

stack s is empty: 
0
stack s1 is empty: 
1
廣告