C++ Array::operator>=() 函式



C++ 的 std::array::operator>=() 函式用於比較兩個陣列,以檢查第一個陣列是否大於或等於第二個陣列。它執行字典序比較,這意味著它按順序比較元素,從第一個開始,並在找到差異時停止。

語法

以下是 std::array::operator>=() 函式的語法。

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

引數

  • lhs, rhs − 表示陣列容器。

返回值

如果第一個陣列容器大於或等於第二個陣列容器,則返回 true,否則返回 false。

異常

此函式從不丟擲異常。

時間複雜度

線性,即 O(n)

示例 1

在以下示例中,我們將考慮 operator>=() 函式的基本用法。

#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;
}

輸出

以上程式碼的輸出如下:

a is greater than or equal to b.

示例 2

考慮以下示例,我們將使用 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;
}

輸出

以上程式碼的輸出如下:

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) {
      |         ~ ^~ ~
      |         |    |

示例 3

讓我們看看以下示例,我們將使用 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;
}

輸出

如果我們執行以上程式碼,它將生成以下輸出:

x is greater than or equal to y.
array.htm
廣告