如何计算预定义数组中的元素数
How to count the number of elements in an predefined array
我想计算数组中元素的实际数量。但是如果我使用 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 来实现此行为。声明简单数组意味着在堆上分配足够的内存。没有办法确定此内存是否被有效的东西"占用",因为总有一些东西(分配后数组的每个索引都有随机值(。
相关文章:
- 数组元素打印的递归方法
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 为什么使用数组元素查找最大数字的程序不起作用?
- 数组元素更改值?
- 如何访问宏中定义的数组元素
- 将数组元素递增 1
- C++函数,它将数组、谓词和运算符作为参数,并将运算符应用于满足谓词的数组元素
- 存储指向动态数组元素的指针
- C++通过别名指针以静默方式将错误的类型分配给数组元素
- 在 std::map 中插入数组元素
- 使用指针访问数组元素时出现意外结果
- c++ 使用动态分配运算符反向数组元素
- 为什么在 c++ 中分配 char 数组元素时,分配的字符会被销毁?
- 缺少数组元素问题
- 如何在类中制作 2D 数组元素,然后在其构造函数中指定其维度?
- 创建一个函数来转换数组元素的类型并返回数组的地址
- 删除在结构 c++ 中声明的数组元素
- Getter 和 Setter 用于类 C++ 中的数组元素
- 尝试递归获取数组元素的总和
- 使用SWIG将numpy数组元素(int)传递给c++int