C++ Stack::operator<= 函式



棧是一種遵循 LIFO(後進先出)原則的基本資料結構,這意味著最後新增的元素將首先被移除。

C++ 函式std::stack::operator<=比較兩個棧,確定第一個棧是否小於或等於第二個棧。它評估棧的大小和元素進行逐個比較,以確定它們之間的關係。

語法

以下是 std::stack::operator<= 函式的語法:

bool operator<=(const stack <Type, Container>& left, const stack <Type, Container>& right);

引數

  • left - 一個 stack 型別的物件。
  • right - 一個 stack 型別的物件。

返回值

如果左側的棧小於或等於右側的棧,則返回 true,否則返回 false。

示例 1

讓我們來看下面的例子,我們將使用 <= 運算子比較棧內的元素。

#include <iostream>
#include <stack>

int main(){
   std::stack<int> x;
   x.push(1);
   x.push(2);
   x.push(3);
   if (x.top() <= 5) {
      std::cout << "Elements are Lessthan Or Equal to 5";
   } else {
      std::cout << "Elements are Greaterthan 5";
   }
   return 0;
}

輸出

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

Elements are Lessthan Or Equal to 5

示例 2

考慮下面的例子,我們將比較兩個棧的大小。

#include <iostream>
#include <stack>

int main(){
   std::stack<int> x, y;
   x.push(11);
   x.push(25);
   y.push(16);
   if (x.size() <= y.size()) {
      std::cout << "X is Lessthan Or Equal To Y";
   } else {
      std::cout << "X Has More Elements Compared To Y";
   }
   return 0;
}

輸出

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

X Has More Elements Compared To Y

示例 3

在下面的例子中,我們將檢查一個棧是否為空或小於或等於另一個棧。

#include <iostream>
#include <stack>

int main(){
   std::stack<int> a, b;
   a.push(12);
   if (a.empty() || a <= b) {
      std::cout << "True";
   } else {
      std::cout << "False";
   }
   return 0;
}

輸出

以上程式碼的輸出如下:

False
廣告