出现“必须调用非静态成员函数的引用”的错误

问题描述 投票:0回答:2

我无法理解这个错误的含义以及导致它的原因。

这是我的代码,请帮我指出错误:

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;
    }
};

我在

sort()
调用中收到错误,确切的错误是:

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

我在 StackOverflow 上搜索并找到了不同代码的解释,但我无法正确理解它。

c++ error-handling static-members pointer-to-member
2个回答
1
投票

std::sort()
需要一个Compare的函数对象,它可以是一个自由函数,一个静态类方法,一个仿函数等。可以按原样调用的东西。

您正在尝试传入一个非静态类方法,这将不起作用,因为

sortbysec()
需要一个对象实例来调用它,因此有一个隐藏的
this
参数,而
std::sort()
无法传入该参数调用该方法时。

解决错误的最简单方法是将

sortbysec()
设为
static
,因为它不使用
Solution
类的任何成员,例如:

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

否则,您可以使用

std::bind()
创建一个函子,将
Solution
对象与
sortbysec
方法联系起来,这样就可以在不指定对象的情况下调用它,例如:

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

或者,使用 lambda 来捕获

this
,例如:

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

在 C++14 及更高版本中可以通过使用

auto
进行一些简化,例如:

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

0
投票

而不是这个:

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

这个:

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

或者正如评论所说,只需将排序函数声明为静态即可。

此外,您的代码仍然无法通过此更改进行编译,因为

v
的类型为
vector<pair<int,int>>
并且与您的返回类型
<vector<int>

不匹配
© www.soinside.com 2019 - 2024. All rights reserved.