C++ Stack::operator> Function



In C++, Stacks provide a flexible toolset for managing date in a LIFO(Last-In-First-Out) manner, meaning that the last added element will be removed first. one of the essential function is std::stack::operator> is used to compare two stacks. It evaluates if one stack is greater than another based on their contents, helping in sirting or prioritization tasks.

Syntax

Following is the Syntax for std::stack::operator> function −

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

Parameters

  • left − An object of type stack.
  • right − An object of type stack.

Return value

It returns true if the stack on the left side of the operator is greaterthan the stack on the rightside, otherwise false.

Example 1

Let's look at the following where we are going to compare the contents of the two stacks.

#include <iostream>
#include <stack>

int main(){
   std::stack<int> x, y;
   x.push(2);
   x.push(4);
   x.push(6);
   y.push(1);
   y.push(3);
   y.push(5);
   if (x > y) {
      std::cout << "TRUE" << std::endl;
   } else {
      std::cout << "FALSE" << std::endl;
   }
   return 0;
}

Output

Let us compile and run the above program, this will produce the following result −

TRUE

Example 2

Considering the following example, where we are going to compare the size of the two stacks.

#include <iostream>
#include <stack>

int main(){
   std::stack<int> a, b;
   a.push(2);
   a.push(4);
   b.push(1);
   b.push(3);
   b.push(5);
   if (a.size() > b.size()) {
      std::cout << "a is greaterthan b";
   } else {
      std::cout << "a is not greaterthan b";
   }
   return 0;
}

Output

If we run the above code it will generate the following output −

a is not greaterthan b

Example 3

In the following example, we are going to see the usage of the std::stack::operator> function.

#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 s2." << endl;
   s2.push(7);
   if (!(s1 > s2))
      cout << "Stack s1 is not greater than s2." << endl;
   return 0;
}

Output

Output of the above code is as follows −

Stack s1 is greater than s2.
Stack s1 is not greater than s2.
Advertisements