Counting occurences of value in an array, and duplicates

Hello.
I have to find the occurences of every element in an array, but I don't know how to get rid of duplicates.

Example:
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
#include "stdafx.h"
#include <iostream>
using namespace std;

int main() {
	int numbers[10];
	cout << "Array Values: ";
	for (int i = 0; i < 10; i++)
	{
		numbers[i] = rand() % 21; // 1-20 Randomly
		cout << numbers[i] << " ";
	}	
	cout << endl;
	int counter = 0, t;
	for (int i = 0; i < 10; i++)
	{
		t = numbers[i];
		for (int j = 0; j < 10; j++)
		{
			if (numbers[j] == t)
			{
				counter++;
			}
		}
		cout << numbers[i] << " occured " << counter << " times" << endl;
		counter = 0;
	}
	system("pause");
	return 0;
}


Output

1
2
3
4
5
6
20 8 13 20 8
20 occured 2 times
8 occured 1 times
13 occured 1 times
20 occured 2 times
8 occured 1 times
Last edited on
One approach is to create a dynamic two-column table, where the first column has values and the second has corresponding counts. When you get next value, it either is already in the table and its count has to be incremented, or the new value has to be added to the table as new row, with count = 1.


A second approach is to somehow mark the elements of the array that have already been used.


Third approach is to first sort the array.
a dynamic two-column table
...better known as "map"?
1
2
3
std::map<int, int> m;
for(int n : numbers) ++m[n];
for(auto& p : m) std::cout << p.first << " occured " << p.second << " times\n";

Last edited on
Topic archived. No new replies allowed.