#include <iostream>
using namespace std;
int main()
{
const int ARRAY_SIZE = 10;
int value[ARRAY_SIZE] = { 1, 2, 3, 4, 3, 4, 2, 3, 5, 6};
int value2[100];
for (int i = 0; i < ARRAY_SIZE; i )
{
for (int j = i 1; j <= ARRAY_SIZE; j )
{
if (value[i] == value[j])
{
cout << value[i] << " ";
}
}
}
return 0;
}
The output is
2 3 3 4 3
How can I make the output become 2 3 4
?
Edit: I'm trying to print all numbers appearing more than once in the value array
I think I should create one more array to store value, but I stuck with it and don't know how to do it.
CodePudding user response:
It helps considerably to sort your array. Then you only need two indices:
- a write index, starting at
0
- a read index, starting at
1
Loop over your array using the read index. For every array[read]
that has a duplicate value at array[read-1]
, IFF that value also does not exist at array[write]
, then copy it over and increment your write index.
Finally, the new length of your data is equal to your write index.
CodePudding user response:
You can use a std::map
to count the number of times a value is in the array. If the number appears 2 or more times, then print it.
#include <iostream>
#include <map>
int main()
{
const int ARRAY_SIZE = 10;
int value[ARRAY_SIZE] = { 1, 2, 3, 4, 3, 4, 2, 3, 5, 6};
std::map <int, int> mp;
for(int i : value)
mp[i];
for(const auto& p : mp)
if(p.second > 1)
std::cout << p.first << ' ';
}
Link.