C++ 数组::size() 函数



C++ 的std::array::size()函数用于返回数组容器中元素的数量。大小在编译时已知,使数组更有效率。此函数对于在无需手动跟踪大小的情况下检索数组中元素的确切数量很有用。

语法

以下是 std::array::size() 函数的语法。

constexpr size_type size() noexcept;

参数

它不接受任何参数。

返回值

它返回数组中元素的数量。

异常

此函数从不抛出异常。

时间复杂度

常数,即 O(1)

示例 1

在以下示例中,我们将考虑 size() 函数的基本用法。

#include <iostream>
#include <array>
int main() {
   std::array < int, 5 > arr = {1,3,5,7,9};
   std::cout << "Size of array : " << arr.size() << std::endl;
   return 0;
}

输出

以上代码的输出如下:

Size of array : 5

示例 2

考虑以下示例,我们将根据索引修改数组。

#include <iostream>
#include <array>
int main() {
   std::array < int, 4 > array = {0};
   for (size_t a = 0; a < array.size(); ++a) {
      array[a] = a * 2;
   }
   for (size_t x = 0; x < array.size(); ++x) {
      std::cout << "array[" << x << "] = " << array[x] << std::endl;
   }
   return 0;
}

输出

以上代码的输出如下:

array[0] = 0
array[1] = 2
array[2] = 4
array[3] = 6

示例 3

让我们看下面的例子,我们将比较两个数组。

#include <iostream>
#include <array>
int main() {
   std::array < int, 4 > x = {1,2,3,4};
   std::array < int, 2 > y = {2,4};
   if (x.size() < y.size()) {
      std::cout << "x is smaller than y" << std::endl;
   } else {
      std::cout << "x is greater than y" << std::endl;
   }
   return 0;
}

输出

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

x is greater than y
array.htm
广告

© . All rights reserved.