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



C++ 的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, 3 > x = {11,22,33};
   std::array < int, 3 > y = {11,22,33};
   if (x == y) {
      std::cout << "Arrays are equal." << std::endl;
   } else {
      std::cout << "Arrays are not equal." << std::endl;
   }
   return 0;
}

輸出

以上程式碼的輸出如下:

Arrays are equal.

示例 2

考慮以下示例,我們將比較兩個具有不同值的陣列。

#include <iostream>
#include <array>
int main() {
   std::array < int, 3 > a = {11,22,33};
   std::array < int, 3 > b = {66,88,22};
   if (a == b) {
      std::cout << "Arrays are equal" << std::endl;
   } else {
      std::cout << "Arrays are not equal" << std::endl;
   }
   return 0;
}

輸出

以上程式碼的輸出如下:

Arrays are not equal

示例 3

讓我們看一下下面的示例,我們將比較不同大小的陣列並觀察輸出。

#include <iostream>
#include <array>
int main() {
   std::array < int, 2 > x = {1,2};
   std::array < int, 3 > y = {2,3,4};
   if (x == y) {
      std::cout << "Arrays are equal" << std::endl;
   } else {
      std::cout << "Arrays are not equal" << 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>')
array.htm
廣告