在C ++中筛选出数组中的重复值 [英] Filter out duplicate values in array in C++
问题描述
例如,我有一排十个数字:
I have a row of ten numbers for example:
5 5 6 7 5 9 4 2 2 7
5 5 6 7 5 9 4 2 2 7
现在,我想要一个程序,该程序可以查找所有重复项,并在控制台中将它们给出,例如3次5次,2次2次,2次7次.虽然我确实编写了一种算法,该算法可以在一排数字中查找重复项,但是我无法如所述在控制台中将它们给出.我的程序将输出:
Now I want a program that finds all duplicates and gives them out in the console like 3 times 5, 2 times 2, 2 times 7. While I did code an algorithm that finds duplicates in a row of numbers I can't give them out in the console as described. My program will output:
3 times 5
2 times 5
2 times 7
2 times 2
我该如何解决这个问题?
How can I solve this problem?
#include <iostream>
using namespace std;
int main()
{
int arr[10];
int i,j;
int z = 1;
for(i = 0; i < 10; i++) {
cin >> arr[i];
}
for(i = 0; i < 10; i++){
for(j = i+1; j < 10; j++){
if(arr[i] == arr[j]){
z++;
}
}
if(z >= 2){
cout << z << " times " << arr[i] << endl;
z = 1;
}
}
return 0;
}
推荐答案
您需要检查以前是否未找到 arr [i]
,例如:
You need to check that arr[i]
is not already found before, like this for example:
if(z >= 2) {
int found_before = 0;
for(j = 0; j < i; ++j)
if(arr[i] == arr[j])
found_before = 1;
if(!found_before)
cout << z << " times " << arr[i] << endl;
z = 1;
}
将打印:
3 times 5
2 times 7
2 times 2
那样,您就不会再次打印 5
.
That way you don't print 5
again.
使用您的代码,它将打印出它发现5次3次(对于数组中的前5个),然后当它移至数组中的后5个时,它将忘记数组中的前5个,并报告它两次发现5(自身和数组的第5个数字).
With your code it would print that it found 5 three times (for the first 5 in your array), and then when it would move to he second 5 in your array, it would forgot about the first 5 in your array, and report that it found 5 twice (itself and the 5th number of the array).
这篇关于在C ++中筛选出数组中的重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!