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



The C++ atd::array::operator!=() function is used to compare two array objects for inequality. This comparison is done element by element, and if any element differs between the two arrays, the function concludes they are not equal. It return true if the arrays differ in size or in any of their corresponding elements, 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 not 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,3};
   std::array < int, 3 > y = {11,4,33};
   if (x != y) {
      std::cout << "Arrays are not equal." << std::endl;
   } else {
      std::cout << "Arrays are equal." << std::endl;
   }
   return 0;
}

Output

Output of the above code is as follows −

Arrays are not equal.

Example 2

Let's look at the following example, where we are going to consider the two identical arrays and using the operator!=().

#include <iostream>
#include <array>
int main() {
   std::array < char, 2 > a = {'x','y'};
   std::array < char, 2 > b = {'x','y'};
   if (a != b) {
      std::cout << "Arrays are not equal." << std::endl;
   } else {
      std::cout << "Arrays are equal." << std::endl;
   }
   return 0;
}

Output

Following is the output of the above code −

Arrays are equal.

Example 3

Consider the following example, where we are going to apply the operator!=() on the two different size array 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 not equal." << std::endl;
   } else {
      std::cout << "Arrays are 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:9: error: expected ')' before '!' token
    6 |    if (x! == y) {
      |       ~ ^
array.htm
Advertisements