C++ Stack::operator== 函式



C++ 函式std::stack::operator==是一個二元運算子,用於測試兩個棧是否相等。

此函式不接受任何引數,並且是const成員函式。“const”關鍵字表示該函式不會修改棧。如果兩個棧的元素和大小相等,則返回布林值 true,否則返回 false。

二元運算符采用兩個運算元來執行特定的操作,例如加法、減法、乘法、除法或比較。它由符號或關鍵字表示,例如 +、-、*、/ 和 ==。

語法

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

bool stack1 == stack2 

引數

  • stack1 - 第一個棧。
  • stack2 - 第二個棧。

返回值

如果兩個棧相等,則返回 true,否則返回 false。

示例 1

以下示例演示了透過比較兩個包含相同元素且大小相同的棧來使用 std::stack::operator== 函式。

首先,我們建立兩個棧 's1' 和 's2',並將元素 '1 - 5' 插入到兩個棧中。然後,我們使用 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);
   }
   if (s1 == s2){
      cout << "Both stacks are equal." << endl;
   }else {
      cout << "Both stacks are not equal." << endl;
   }
}

輸出

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

Both stacks are equal.

示例 2

這裡,我們比較兩個非空棧,它們包含不同的元素但大小相同。

最初,我們建立兩個棧 's1' 和 's2',並將元素 '1'、'2' 和 '3' 插入到 's1' 中,並將 '3'、'2' 和 '1' 插入到 's2' 中。然後,我們使用 operator== 函式比較它們。

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

int main(void) {
   stack<int> s1;
   stack<int> s2;
   s1.push(1);
   s1.push(2);
   s1.push(3);
   s2.push(3);
   s2.push(2);
   s2.push(1);
   if (s1 == s2) {
      cout << "Both stacks are equal." << endl;
   }else {
      cout << "Both stacks are not equal." << endl;
   }
}

輸出

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

Both stacks are not equal.

示例 3

現在,我們比較兩個非空棧,它們包含不同的元素且大小不同。

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

int main(void) {
   stack<int> s1;
   stack<int> s2;
   s1.push(1);
   s1.push(2);
   s2.push(1);
   if (s1 == s2) {
      cout << "Both stacks are equal." << endl;
   }else {
      cout << "Both stacks are not equal." << endl;
   }
}

輸出

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

Both stacks are not equal.

示例 4

在以下示例中,我們嘗試使用 operator== 函式比較兩個空棧 's1' 和 's2':

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

int main(void) {
   stack<int> s1;
   stack<int> s2;
   if (s1 == s2) {
      cout << "Both stacks are equal." << endl;
   }else {
      cout << "Both stacks are not equal." << endl;
   }
}

輸出

以上程式碼的輸出如下:

Both stacks are equal.
廣告