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



The C++ std::array::operator>=() function is used to compare two arrays to check whether the first array is greater than or equal to the second array. It perform a lexicographical comparison, means it compare elements in order, starting from the first, and stops as soon as the difference is found.

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 first array container is greater or equal to the second 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, 2 > a = {1,22};
   std::array < int, 2 > b = {1,2};
   if (a >= b) {
      std::cout << "a is greater than or equal to b.";
   } else {
      std::cout << "a is less than b.";
   }
   return 0;
}

Output

Output of the above code is as follows −

a is greater than or equal to b.

Example 2

Consider the following example, where we are going to compare the array of different size using operator>=().

#include <iostream>
#include <array>
int main() {
   std::array < int, 2 > x = {11,22};
   std::array < int, 3 > y = {11,22,33};
   if (x >= y) {
      std::cout << "x is greater than or equal to y.";
   } else {
      std::cout << "x is less than y.";
   }
   return 0;
}

Output

Following is the output of the above code −

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>')
    6 |     if (x >= y) {
      |         ~ ^~ ~
      |         |    |

Example 3

Let's look at the following example, where we are going to compare the identical arrays using operator>=().

#include <iostream>
#include <array>
int main() {
   std::array < int, 2 > x = {'a','b'};
   std::array < int, 2 > y = {'a','b'};
   if (x >= y) {
      std::cout << "x is greater than or equal to y.";
   } else {
      std::cout << "x is less than y.";
   }
   return 0;
}

Output

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

x is greater than or equal to y.
array.htm
Advertisements