C++ Array::operator>() 函数



C++ 的 std::array::operator>() 函数是一个比较运算符,用于检查一个数组是否大于另一个数组。比较从第一个元素开始,依次进行,直到找到差异。如果第一个数组大于第二个数组,则返回 true,否则返回 false。

语法

以下是 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 > x = {1,22};
   std::array < int, 2 > y = {11,32};
   if (x > y) {
      std::cout << "x is greater than y." << std::endl;
   } else {
      std::cout << "x is not greater than y." << std::endl;
   }
   return 0;
}

输出

以上代码的输出如下:

x is not greater than y.

示例 2

考虑以下示例,我们将对不同大小的数组使用 operator>() 并观察输出。

#include <iostream>
#include <array>
int main() {
   std::array < int, 2 > x = {1,2};
   std::array < int, 3 > y = {1,2,5};
   if (x > y) {
      std::cout << "x is greater than y." << std::endl;
   } else {
      std::cout << "x is not greater than y." << std::endl;
   }
   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) {
      |         ~ ^ ~
      |         |   |
      |         |   array<[...],3>
      |         array<[...],2>

示例 3

让我们看看下面的示例,我们将考虑相同的数组并应用 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 << "a is greater than b." << std::endl;
   } else {
      std::cout << "a is not greater than b." << std::endl;
   }
   return 0;
}

输出

如果我们运行以上代码,它将生成以下输出:

a is not greater than b.
array.htm
广告
© . All rights reserved.