C++ Stack::operator!= 函式



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

此函式不接受任何引數,並且是一個const成員函式。“const”關鍵字表示該函式不會修改棧。它是operator==函式的補集(相反)運算子。如果兩個棧的元素和大小不相等,則返回布林值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 not equal." << endl;
   }else {
      cout << "Both stacks are 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 not equal." << endl;
   }else {
      cout << "Both stacks are 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 not equal." << endl;
   }else {
      cout << "Both stacks are 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 not equal." << endl;
   }else {
      cout << "Both stacks are equal." << endl;
   }
}

輸出

上述程式碼的輸出如下:

Both stacks are equal.
廣告