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, 3 > x = {1,2,33};
   std::array < int, 3 > y = {11,4,23};
   if (x < y) {
      std::cout << "x is less than y." << std::endl;
   } else {
      std::cout << "arr1 is not less than y." << std::endl;
   }
   return 0;
}

輸出

以上程式碼的輸出如下:

x is less than y.

示例 2

考慮下面的示例,我們將使用相同的陣列並應用 operator<()。

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

輸出

以上程式碼的輸出如下:

x is not less than y.
array.htm
廣告