简体   繁体   中英

Leetcode C++ error: reference to non-static member function must be called

when I was doing Leetcode, I wrote my codes as follows:

class Solution {
public:
    bool compare(vector<int> a, vector<int> b)
    {
        return a[1] > b[1];
    };
    
    int maximumUnits(vector<vector<int>>& boxTypes, int truckSize) {
        sort(boxTypes.begin(), boxTypes.end(), compare);
    }
};

And then it told me "error: reference to non-static member function must be called", the problem is on "compare" in sort function. But the weird thing is, when I run it on local compiler, it totally works. Could someone tell me why?

Just add static in front of your comparator function

class Solution {
public:
    static bool mycomp(const pair<int,int> &a, const pair<int,int> &b)
    {
        if(a.first==b.first)
        {
            return a.second < b.second;
        }
        return a.first < b.first;
    }
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<pair<int,int>> temp;
        for(int i=0; i<nums.size(); i++)
        {
            temp.emplace_back(make_pair(nums[i], i));
        }
        
        sort(temp.begin(), temp.end(), mycomp);       
        
        return nums;
    }
};

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