Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

C++ Array::operator==() Function



The C++ operator==() function is used to compare two array objects for equality. It checks whether the arrays have the same size and if all corresponding elements are equal. This function returns true if both the conditions are met, otherwise it returns false.

Syntax

Following is the syntax for std::array::operator==() function.

bool operator== ( const array<T,N>& lhs, const array<T,N>& rhs );

Parameters

  • lhs, rhs − It indicates the array containers.

Return Value

It returns true if array containers are identical otherwise false.

Exceptions

This function never throws exception.

Time complexity

Linear i.e. O(n)

Example 1

In the following example, we are going to consider the basic usage of the operator==() function.

#include <iostream>
#include <array>
int main() {
   std::array < int, 3 > x = {11,22,33};
   std::array < int, 3 > y = {11,22,33};
   if (x == y) {
      std::cout << "Arrays are equal." << std::endl;
   } else {
      std::cout << "Arrays are not equal." << std::endl;
   }
   return 0;
}

Output

Output of the above code is as follows −

Arrays are equal.

Example 2

Consider the following example, where we are going to compare the two arrays of different values.

#include <iostream>
#include <array>
int main() {
   std::array < int, 3 > a = {11,22,33};
   std::array < int, 3 > b = {66,88,22};
   if (a == b) {
      std::cout << "Arrays are equal" << std::endl;
   } else {
      std::cout << "Arrays are not equal" << std::endl;
   }
   return 0;
}

Output

Following is the output of the above code −

Arrays are not equal

Example 3

Let's look at the following example, where we are going to compare the arrays of different sizes and observing the output.

#include <iostream>
#include <array>
int main() {
   std::array < int, 2 > x = {1,2};
   std::array < int, 3 > y = {2,3,4};
   if (x == y) {
      std::cout << "Arrays are equal" << std::endl;
   } else {
      std::cout << "Arrays are not equal" << std::endl;
   }
   return 0;
}

Output

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

main.cpp: In function 'int main()':
main.cpp:6:11: error: no match for 'operator==' (operand types are 'std::array<int, 2>' and 'std::array<int, 3>')
array.htm
Advertisements