Find the frequency of each element in an array in c++

C++ program for Find the frequency of each element in an array. Here problem description and explanation.

// Include header file
#include <iostream>
#include <unordered_map>
using namespace std;
class Occurrence
{
	public:
		// Function which is display array elements
		void display(int arr[], int n)
		{
			for (int i = 0; i < n; ++i)
			{
				cout << "   " << arr[i];
			}
			cout << "\n";
		}
	// Count occurrence of given array
	void frequency(int arr[], int n)
	{
		// Display given array
		this->display(arr, n);
		// Create a empty map
		unordered_map < int, int > map;
		for (int i = 0; i < n; i++)
		{
			if (map.find(arr[i]) != map.end())
			{
				// When key exists then update value
				map[arr[i]] = map[arr[i]] + 1;
			}
			else
			{
				// Add new element
				map[arr[i]] = 1;
			}
		}
		cout << "  Occurrence " << endl;
		//  Display calculated result
		for (auto &key: map)
		{
			cout << "  " << key.first << "  :  " 
                << map[key.first] << endl;
		}
	}
};
int main()
{
	// Array element
	int arr[] = {
		1 , 3 , 2 , 1 , 4 , 2 , 7 , 9 , 1 , 3 , 3 , 4 , 7
	};
  	int n = sizeof(arr) / sizeof(arr[0]);
  	Occurrence task;
	task.frequency(arr, n);
	return 0;
}

Output

   1   3   2   1   4   2   7   9   1   3   3   4   7
  Occurrence
  9  :  1
  7  :  2
  1  :  3
  3  :  3
  2  :  2
  4  :  2


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved