如何计算预定义数组中的元素数

How to count the number of elements in an predefined array

本文关键字:数组 元素 预定义 何计算 计算      更新时间:2023-10-16

我想计算数组中元素的实际数量。但是如果我使用 sizeof(( 语句,它会给我数组的大小。而不是存在的元素数量。

int main()
 {
 int a[10],n;
 a[0]=1;
 a[1]=5;
 a[2]=6;
 n=sizeof(a)/sizeof(a[0]);
 cout<<"The size of array " <<n;
 }

在这里,它给我的 n 值为 10 而不是 3。请向我建议一种在不影响性能的情况下推导出元素数量的方法。

int a[10]; // This would allocate 10 int spaces in the memory;
a[0] = 1;  // You are changing whats inside the first allocated space, but you are not changing the number of items in your C array.

解决方案1(简单(:

#include <vector>
vector<int> a;
a.push_back(1);
a.push_back(2);
size_t size = a.size(); // to get the size of your vector. would return 2. size_t is the actual type returned by size() method and is an unsigned int.

解决方案 2(复杂(:

您可以创建一个可以调用的int变量,例如 每次添加元素时numberOfElements并更新它。此解决方案实际上用于向量类的实现。

如前所述,您应该使用 std::vector 或 std:array 来实现此行为。声明简单数组意味着在堆上分配足够的内存。没有办法确定此内存是否被有效的东西"占用",因为总有一些东西(分配后数组的每个索引都有随机值(。