Getting an error of "Reference to non-static member function must be called"

46 Views Asked by At

I'm not able to understand what this error means, and what is causing it.

Here is my code, please help me to point out the mistake:

class Solution {
public:
    bool sortbysec(const pair<int,int> &a,const pair<int,int> &b)
    {
        return (a.second < b.second);
    }
    vector<int> topKFreAquent(vector<int>& nums, int k) 
    {
        unordered_map<int,int> m;
        for(int i=0;i<nums.size();i++)
        {
            m[nums[i]]++;
        }
        vector<pair<int,int>> v;
        for(auto it = m.begin();it != m.end();it++)
        {
            v.push_back(make_pair(it->first,it->second));
        }
        sort(v.rbegin(),v.rend(),sortbysec);
        v.resize(k);
        return v;
    }
};

I'm getting the error in the sort() call, the exact error is:

Line 19: Char 34: error: reference to non-static member function must be called
        sort(v.rbegin(),v.rend(),sortbysec);
                                 ^~~~~~~~~

I searched on StackOverflow and found an explanation for a different code, but I wasn't able to understand it properly.

2

There are 2 best solutions below

2
selbie On

Instead of this:

sort(v.rbegin(),v.rend(),sortbysec);

This:

sort(v.rbegin(), v.rend(), [this](const pair<int, int>& p1, const pair<int, int>& p2) {
    return this->sortbysec(p1, p2);
});

Or as the comment said, just declare your sort function static.

Also, your code still won't compile with this change because v is of type vector<pair<int,int>> and does not match your return type of <vector<int>

0
Remy Lebeau On

std::sort() expects a Compare-able function object, which can be a free function, a static class method, a functor, etc. Something that can be called on as-is.

You are trying to pass in a non-static class method, which will not work since sortbysec() requires an object instance to call it, and hence has a hidden this parameter, which std::sort() has no way to pass in when calling the method.

The simplest fix to your error would be to just make sortbysec() be static, since it is not using any members of the Solution class, eg:

static bool sortbysec(const std::pair<int,int> &a, const std::pair<int,int> &b)

Otherwise, you can use std::bind() to create a functor that ties the Solution object to the sortbysec method so it can be called without specifying the object, eg:

using namespace std::placeholders;
std::sort(v.rbegin(), v.rend(),
    std::bind(&Solution::sortbysec, this, _1, _2)
);

Or, use a lambda instead to capture this, eg:

std::sort(v.rbegin(), v.rend(),
    [this](const std::pair<int,int> &a, const std::pair<int,int> &b){
        return sortbysec(a, b);
    }
);

Which can be simplified a little in C++14 and later by using auto, eg:

std::sort(v.rbegin(), v.rend(),
    [this](const auto &a, const auto &b){
        return sortbysec(a, b);
    }
);