最近在刷一道算法题时候报错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;
}
};
参考:
2852

被折叠的 条评论
为什么被折叠?



