Search code examples
c++c++11custom-sort

External Data Structure Used in Custom Comparison Function in C++


I have array of numbers and I have to sort them based on there frequency in ascending order
and if both numbers are same then sort them in decreasing order

what I did was I create unordered_map and store number's frequency in map
and Inside custom sort function I used it to sort the numbers

Implemention look's like this

class Solution {
public:
    unordered_map<int,int>map;

    bool operator ()(const int &a,const int &b){
        if(map[a]==map[b])
            return a>b;

        return map[a]<map[b];
    }

    vector<int> frequencySort(vector<int>& nums) {
        vector<int>answer;

        for(auto num:nums)
            map[num]++;

        sort(nums.begin(),nums.end(),Solution());

        return nums;
    }
};

but when I use this custom function I gives me wrong answe like

for input nums = [1,1,2,2,2,3]
output is [3,2,2,2,1,1]

which is not expected !! but functions implementation looks good

so what expexted is
Expected [3,1,1,2,2,2]

to achive this I see solution and they used lamda function for custom sorting
Implementation of lamda function is like

sort(nums.begin(),nums.end(),[&](int a, int b) {
            if (map[a] == map[b]) {
                return a > b;
            }
            return map[a] < map[b];
        });

body part of my function and lamda function is similiar
but why I am getting wrong answer ?

Thank you


Solution

  • As Quimby has already mentioned in the comments, you are passing a temporary instance of Solution as the Compare parameter of std::sort but this temporary is a new instance of Solution and all it’s member variables and member functions are in the default state. In this default state, Solution::map is a default constructed std::unordered_map and not the std::unordered_map currently in the original instance of Solution so it has no knowledge of the frequencies currently stored in the original. To use the original as the comparator function for std::sort, pass the original to std::sort.


    std::sort(nums.begin(),nums.end(), *this);