C数组循环通过
除了遍历数组的每个元素外,还可以仅遍历具有赋值的元素吗?
Instead of looping through each element of an array is it possible to loop through only elements which have assignments?
在下面的示例中,我只想遍历三个元素,而不是遍历数组中的每个元素。我有什么选择?当基于某些逻辑仅分配了数千个元素时,我讨厌遍历数千个元素。
In the following example I would like to loop through only three elements instead of looping through each element in the array. What are my options ? I hate to loop through thousands of elements when only handful from them are assigned based on certain logic.
main()
{
int i, intArray[10000];
intArray[334] = 30;
intArray[563] = 50;
intArray[989] = 90;
for (i = 0; i < 10000; i++)
{
printf("%d\n", intArray[i]);
}
}
感谢您阅读这篇文章。抱歉,如果重新发布。我不会在论坛中找到类似的问题。
Thank you for reading the post. Sorry if it a re-post. I would not find similar question in the forum.
仅间接地:
#include <stdio.h>
int main(void)
{
int i, intArray[10000];
int active[10000];
int n_active = 0;
intArray[334] = 30;
active[n_active++] = 334;
intArray[563] = 50;
active[n_active++] = 563;
intArray[989] = 90;
active[n_active++] = 989;
for (i = 0; i < n_active; i++)
printf("%d\n", intArray[active[i]]);
return 0;
}
或者,更简洁但不清楚的是:
Or, more succinctly but not more clearly:
#include <stdio.h>
int main(void)
{
int i, intArray[10000];
int active[10000];
int n_active = 0;
intArray[active[n_active++]=334] = 30;
intArray[active[n_active++]=563] = 50;
intArray[active[n_active++]=989] = 90;
for (i = 0; i < n_active; i++)
printf("%d\n", intArray[active[i]]);
return 0;
}
如果同一索引分配了多个,则这两个程序都会受到影响(该索引将两次存储在 active
数组中)。就目前而言,它也不会检查 active
数组是否溢出(但这应该不成问题;假设是只有几行是填充),然后按显示顺序(而不是键顺序)存储索引。所有这些缺陷都可以解决,但是需要更多代码(可能需要一个或两个函数)。
Both of these programs will suffer if there's more than one assignment to the same index (that index will be stored in the active
array twice). As it stands, it also doesn't check for overflow of the active
array (but that shouldn't be a problem; the hypothesis is that only a few of the rows are populated), and the indexes are stored in the order that they're presented — not in key order. All these defects can be fixed, but take more code (it would probably need to be a function or two).