C++ Stack::operator>= 函式



C++ 函式std::stack::operator>=用於比較兩個棧。它檢查一個棧中的元素是否大於或等於另一個棧中的元素。如果棧的大小不同,此函式可能會返回未定義的結果。如果第一個棧的元素大於或等於第二個棧的對應元素,則返回true;否則返回false。

語法

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

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

引數

  • left - 型別為stack的物件。
  • right - 型別為stack的物件。

返回值

如果第一個棧大於或等於第二個棧,則返回true;否則返回false。

示例1

讓我們來看下面的例子,我們將比較兩個棧x和y的大小。

#include <iostream>
#include <stack>

int main() {
   std::stack<int> x, y;
   x.push(11);
   x.push(22);
   x.push(33);
   y.push(44);
   y.push(55);
   if (x.size() >= y.size()) {
      std::cout << "True";
   } else {
      std::cout << "False";
   }

   return 0;
}

輸出

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

True

示例2

考慮下面的例子,我們將檢查棧的大小是否大於或等於指定的值。

#include <iostream>
#include <stack>

int main(){
   std::stack<int> x;
   x.push(11);
   x.push(22);
   int value = 4;
   if (x.size() >= value) {
      std::cout << "True, Stack size is greaterthan or equal to" <<value<<".";
   } else {
      std::cout << "False, Stack size is Not greaterthan or equal to " <<value<<".";
   }
   return 0;
}

輸出

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

False, Stack size is Not greaterthan or equal to 4.

示例3

在下面的例子中,我們將觀察std::stack::operator>=函式的用法。

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

int main(void){
   stack<int> s1;
   stack<int> s2;
   for (int i = 0; i < 5; ++i) {
      s1.push(i + 1);
      s2.push(i + 1);
   }
   s1.push(6);
   if (s1 >= s2)
      cout << "Stack s1 is greater than or equal to s2." << endl;
   s2.push(7);
   if (!(s1 >= s2))
      cout << "Stack s1 is not greater than or equal to s2." << endl;
   return 0;
}

輸出

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

Stack s1 is greater than or equal to s2.
Stack s1 is not greater than or equal to s2.
廣告