'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?
Solution 1:[1]
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;
}
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Bhiman Kumar Baghel |