简体   繁体   中英

Reference to non-static Member Function

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)

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.

在 C++ 中,即使您使用自定义比较器,也无法对地图进行排序。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM