How to print only duplicates in an array

Oct 27, 2019 at 1:08pm
Hi,
I want to print only those elements of an array which were repeated.
This is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
int main()
{	
	int val;
	int* tab = NULL;
	int n;

	cout << "How many elements: "; 
	cin >> n;

	tab = (int*)malloc(n * sizeof(int));

	for (int i = 0; i < n; i++)
	{
		cin >> val;
		tab[i] = val;
	}
	
	cout << "\nRepeated elements: " << endl;
	
	for (int i = 0; i < n; i++)
	{
		for(int j = i + 1; j < n; j++) 
		{
			if (tab[i] == tab[j])
				cout << tab[j];
		}
	}


	free(tab);

	return 0;
}


This code works, but only for those elements which were repeated once, for example, for this input of 10 elements:
5 5 1 2 3 1 6 7 9 8

the output will be: 5 1
and this works fine,

but then again, another input: 5 5 5 5 2 3 9 9 1 1

and the output is:
5 5 5 5 5 5 9 1

and there I don't know how to print "5" only once...
Any help would be appreciated... Thanks :)
Oct 27, 2019 at 1:22pm
You could use a map<int, int>

Each time you find a number, add one to that value's count in the map (or, if it's te first time you've seen it, create its count in the map, with value 1).

Then go through the map, and output every number for which the count is more than one.
Oct 27, 2019 at 8:01pm
I didn't know that something like map<..> existed, thanks.
I hoped there is maybe an easier way with for loops and conditions to achieve this, but this map<> thing seems more clear.

Thanks again
Oct 28, 2019 at 2:42am
A map is also called an associative array, and it is an associative array that you use to create histograms.

And a histogram is exactly what Repeater has suggested you use.
Topic archived. No new replies allowed.