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.
广告

© . All rights reserved.