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