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

© . All rights reserved.