sort函数使用cmp出错Line 22: Char 38: error: reference to non-static member function must be called

出错代码

class Solution {
public:
    int math(int n)
    {
        int ans = 0;
        while (n)
        {
            n &= (n - 1);
            ans++;
        }
        return ans;
    }
    bool    cmp(int x, int y)
    {
        if (math(x) == math(y))
            return  x < y;
        else
            return  math(x) < math(y);
    }
    vector<int> sortByBits(vector<int>& arr)
    {
        sort(arr.begin(), arr.end(), cmp);
        return  arr;
    }
};

解决方法:将其它成员函数(cmp函数)移动到public外,或者加上static

 

class Solution {
public:
    int math(int n)
    {
        int ans = 0;
        while (n)
        {
            n &= (n - 1);
            ans++;
        }
        return ans;
    }
    static  bool    cmp(int x, int y)
    {
        if (math(x) == math(y))
            return  x < y;
        else
            return  math(x) < math(y);
    }
    vector<int> sortByBits(vector<int>& arr)
    {
        sort(arr.begin(), arr.end(), cmp);
        return  arr;
    }
};

posted @ 2022-07-29 12:10  Gustavo09  阅读(74)  评论(0)    收藏  举报