0

I have sorted the array using unordered_map, and the code is a below

 #include <bits/stdc++.h>
 using namespace std;

 void countFreq(int arr[], int n, std::unordered_map<int, int> &mp)
 {
     for (int i = 0; i < n; i++)
         mp[arr[i]]++;
 }
 
 int main()
 {
     int arr[] = { 300, 300, 300, 200, 200, 200, 200, 150, 100, 100, 50, 50, 50};
     int n = sizeof(arr) / sizeof(arr[0]);
     unordered_map<int, int> mp;
     countFreq(arr, n, mp);
     for (auto x : mp)
         cout << x.first << " " << x.second << endl;
     return 0;
 }

The output of the code i as follows

    50 3
    100 2
    150 1
    300 3
    200 4

but i need the output, with the freqency updated for each of element as,

    300 3
    200 4
    150 1
    100 2
    50 3

My array is always sorted with duplicate numbers and the size of the array always varies. I need the frequency of occurance of each number in the array in the same was it is sorted as my future logic entirely depends this.

Can any one provide me inputs as to how the above output can be achieved, is this possible using unordered map or should a different approach has be taken? I am new to C++ and using these DS for the first time.

cigien
  • 50,328
  • 7
  • 37
  • 78
Manu
  • 4,584
  • 6
  • 27
  • 37
  • You should use `map` instead if you care about the order of keys. Also, please don't include that header, see https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h – cigien Oct 21 '20 at 18:41

0 Answers0