谁能解释一下下面程序中的 count[array[i]]
是什么意思?
代码的目的是打印数组中所有重复的数字和频率。
#include <stdio.h>
#include <malloc.h>
void duplicate(int array[], int num)
{
int *count = (int *)calloc(sizeof(int), (num - 2));
int i;
printf("duplicate elements present in the given array are ");
for (i = 0; i < num; i++)
{
if (count[array[i]] == 1)
printf(" %d ", array[i]);
else
count[array[i]]++;
}
}
int main()
{
int array[] = {5, 10, 10, 2, 1, 4, 2};
int array_freq = sizeof(array) / sizeof(array[0]);
duplicate(array, array_freq);
getchar();
return 0;
}
最佳答案
这是用于查找数组中重复项的最糟糕的方法。
count[array[i]]++;
因此,array[i]
将返回该索引处的数字,该数字又将用作 count 数组的索引。例如:-
array[4] = {1,2,3,1};
将数组迭代到此将类似于:-
count[array[0]] = count[1] = 1;
count[array[1]] = count[2] = 1;
count[array[2]] = count[3] = 1;
count[array[3]] = count[1] = 2; << Increment the count...
关于c++ - 该声明的含义 count[array[i]],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27089023/