Home > other >  Reference to non-static Member Function
Reference to non-static Member Function

Time:10-15

https://leetcode.com/problems/sort-array-by-increasing-frequency/

In this leetcode question, I wrote the following code:

class Solution {
public:
    bool compare(pair<int,int>p1,pair<int,int>p2)
    {
        if(p1.second<p2.second)
            return true;
        else if(p1.second==p2.second)
        {
            if(p1.first>p2.first)
                return true;
            else
                return false;
        }
        else
            return false;
    }
    vector<int> frequencySort(vector<int>& nums) {
        vector<int>final(nums.size());int k=0;map<int,int>mpp;
        for(int i=0;i<nums.size();i  )
        {
            mpp[nums[i]]  ;
        }
        sort(mpp.begin(),mpp.end(),compare);
        for(auto it:mpp)
        {
            while(it.second)
            {
                final[k  ]=it.first;
                it.second--;
            }
        }
        return final;
    }
};

This gives me the following error:

Line 23: Char 36: error: reference to non-static member function must be called
        sort(mpp.begin(),mpp.end(),compare);
                                   ^~~~~~~

Can someone please point out the mistake? (PS: I am new to Object Oriented Programming)

CodePudding user response:

In C Maps cannot be sorted even if you use a Custom Comparator.

CodePudding user response:

As a workaround you can dump the map's pairs into a std::vector<std::pair<int,int>> first:

std::vector<std::pair<int,int>> intermediate(mpp.begin(), mpp.end());
std::sort(begin(intermediate), end(intermediate), compare);

and then walk intermediate instead.

  • Related