我正在将文件内容读入一个9个元素的数组中。我需要检查这个数组中是否有重复项。我需要在不重新排序或更改数组任何内容的情况下完成这个任务。
我应该如何处理?
用暴力破解的方法。
由于该数组只有9个元素,所以最多只需进行36次比较就可以找到任何重复项:
int count = sizeof(array) / sizeof(array[0]);
for (int i = 0; i < count - 1; i++) { // read comment by @nbro
for (int j = i + 1; j < count; j++) {
if (array[i] == array[j]) {
// do whatever you do in case of a duplicate
}
}
}
sizeof(array)
当然是指 sizeof(array) / sizeof(array[0])
吧? - Alexey Frunzecount - 1
,否则在最后一次迭代时内部循环完全无用。我会编辑答案以反映这个改进。 - nbro// sort a copy of the array with the algorithm you like the most and then...
bool duplicates = false;
for(i = 0; i < 7; i++)
{
if (array[i] == array[i+1])
{
duplicates = true;
break;
}
}
$
不是C标识符中的有效字符,尽管您的编译器可能支持它。哦,当i=8
时,您正在访问一个不存在的数组元素array[9]
。 - Alexey Frunze int main()
{
srand(time(0));
int data[10];
for(int c=0;c<=9;c++)
{
bool found = false;
while(!found)
{
data[c]=rand()%10+1;
found=true;
for(int r=0;r<c;r++)
{
if(data[c]==data[r]) found=false;
}
}
}
for(int c=0;c<=9;c++) cout << data[c] << endl;
return 0;
}