class Solution {
public:
bool comp(int &a,int &b){
return a>b;
}
int findKthLargest(vector<int>& nums, int k) {
vector<int> vec= nums;
sort(vec.begin(),vec.end(),comp); //error: reference to non-static member should be called
cout << vec[k-1];
}
};
此错误的原因是什么?我该如何解决呢?
最佳答案
问题在于您要将成员函数传递给std::sort
,并且由于它是成员函数,因此需要实例来对其进行调用。
您有一些解决方案。
sort(vec.begin(),vec.end(), [this](int i, int j){return comp(i,j);});
sort(vec.begin(), vec.end(), std::bind(&Solution::comp, this, _1, _2));
sort(vec.begin(), vec.end(), std::greater<int>());
struct {
bool operator()(int a, int b) const
{
return a > b;
}
} comp;
.
.
sort(vec.begin(), vec.end(), comp);
附言:
正如其他人已经指出的那样,没有必要在
comp
中使用引用,并确保在findKthLargest
函数中您实际上返回了一些东西。
关于c++ - 对非静态成员的引用应称为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61995188/