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

最近在刷一道算法题时候报错error: reference to non-static member function must be called
原因如下:
非静态成员函数不是常规函数。它们有一个隐藏的隐式指针参数,指向调用它们的对象,它必须与类的实例一起运行。
非静态成员函数是类的一部分,并且与特定的对象实例相关联。在非静态成员函数内部,可以使用this指针访问对象的成员变量和成员函数。非静态成员函数需要通过对象实例调用,而不是通过类名。每个对象实例都有自己的成员变量和成员函数,因此非静态成员函数的行为可能因对象实例的不同而有所不同。我们需要传递一个 this 指针来告诉函数要处理哪个对象,因为它依赖于它而不是静态成员函数。

当我们尝试将非静态成员函数作为函数指针传递给STL算法(如sort函数)时,由于函数指针没有隐含的this指针,因此无法直接使用非静态成员函数作为函数指针。因此我们需要将非静态成员函数转换为静态成员函数或全局函数,或者使用函数对象类。

class Solution {
public:

    static bool cmp_by_value(const pair<int, int>& lhs, const pair<int, int>& rhs) {  
        return lhs.second > rhs.second;  
    }  

    struct CmpByValue {  
        bool operator()(const pair<int, int>& lhs, const pair<int, int>& rhs) {  
            return lhs.second > rhs.second;  
        }  
    };

    vector<int> topKFrequent(vector<int>& nums, int k) {

        map<int, int> count;
      
        for (int i = 0; i < nums.size(); i++) {
            count[nums[i]] += 1;
        }

        // for (auto i = count.begin(); i != count.end(); i++) {
        //     cout << i->first << ' ';
        // }

        // 将map中的元素转存到vector中
        vector<pair<int, int>> sort_count(count.begin(), count.end());
        // 注意,要定义为静态成员函数,否则报error: reference to non-static member function must be called 
        sort(sort_count.begin(), sort_count.end(), cmp_by_value);  
        // sort(sort_count.begin(), sort_count.end(), CmpByValue());

        vector<int> res;
        // for (auto i = count.begin(); i != count.end() && k != 0; i++) {
        //     res.push_back(i->first);
        //     k--;
        // }
        for (int i = 0; i < k; i++) {
            res.push_back(sort_count[i].first);
        }

        return res;
    }
};

参考:

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值