问题描述
我有这样一个数组以下
int arr[32];
这数组可以包含32元。结果
如果我加入该数组像一些数据如下
This array can contain 32 element.
If I added into that array some data like the following
arr[0] = 5;
arr[1] = 10;
arr[2] = 15;
arr[3] = 20;
正如你看到我添加的数据转换成元素 0,1,2,3
和其他元素依旧未初始化或为空。
As you see I added data into elements 0,1,2,3
and the other elements is still not initialized or empty.
现在,如何得到一个只有数据元素计数?
将获得4个元素。
推荐答案
您可以通过多种方式做到这一点 - 一个是保持初始化值计数器:
You could do this in multiple ways - one is to keep counter of initialized values:
arr[0] = 5;
arr[1] = 10;
arr[2] = 15;
arr[3] = 20;
n = 4;
这仅适用,如果你将填补阵列顺序。
This only works if you will fill array sequentially.
其它方式是初始化一些值语义不能是数组的元素阵列
Other way is to initialize array with some value which semantically can't be elements of the array:
int arr[32] = {-1};
在这之后,你可以检查当前的元素包含不同于值 1
。
样品环可以这样进行:
for(i = 0; i < 32 && arr[i] != -1; i++)
{
// do things
}
此外,作为@Jongware在评论中指出 - 如果你不介意的额外空间开销为O(n) - 你可以有额外的标志数组:
Also, as @Jongware pointed out in the comment - if you don't mind spending O(n) of extra space - you could have additional flag array:
int fill[32] = {0};
arr[0] = 5; fill[0] = 1;
arr[1] = 10; fill[1] = 1;
arr[2] = 15; fill[2] = 1;
arr[3] = 20; fill[3] = 1;
您可以节省使用位集一些空间,如果这对你很重要。
You could save some space using bitsets, if that is important for you.
这篇关于得到,它具有在阵列的值元素的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!