C++ Array::empty() 函式



C++ 的std::array::empty()函式用於檢查陣列是否為空。由於std::array是一個固定大小的容器,其大小在編譯時已知,並且不能動態調整大小。對於std::array,此函式始終返回false,因為除非陣列大小為零(這種情況很少見),否則陣列永遠不會為空。

語法

以下是std::array::empty()函式的語法。

constexpr bool empty() noexcept;

引數

此函式不接受任何引數。

返回值

它返回一個布林值,指示陣列是否為空。

異常

此函式永不丟擲異常。

時間複雜度

常數,即 O(1)

示例 1

在下面的示例中,我們將考慮empty()函式的基本用法。

#include <iostream>
#include <array>
using namespace std;
int main() {
   array < int, 10 > myarray {9,12,15,18,21,24,27,30,33,36};
   if (myarray.empty()) {
      cout << "True";
   } else {
      cout << "False";
   }
   return 0;
}

輸出

以上程式碼的輸出如下:

False

示例 2

考慮下面的示例,我們將考慮兩個陣列,一個大小為零,另一個大小為10。

#include <iostream>
#include <array>
using namespace std;
int main(void) {
   array < int, 0 > arr1;
   array < int, 10 > arr2;
   if (arr1.empty())
      cout << "arr1 is empty" << endl;
   else
      cout << "arr1 is not empty" << endl;
   if (arr2.empty())
      cout << "arr2 is empty" << endl;
   else
      cout << "arr2 is not empty" << endl;
}

輸出

以下是以上程式碼的輸出:

arr1 is empty
arr2 is not empty
array.htm
廣告