在leetcode347. 前 K 个高频元素使用sort函数时发生错误:
查阅资料后,我得知这是因为我在类成员函数中调用三个参数的sort(),并且也将mycmp函数定义为类成员函数,需要将cmp函数在类中定义为static。
还有另一种方法就是把mycmp函数定义在solution类的外面,就没有这个问题。
代码如下:
bool mycmp(const pair<int,int>&p1,const pair<int,int>&p2){
return p1.second>p2.second;
}
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int,int>map1;
for(int i=0;i<nums.size();i++){
map1[nums[i]]++;
}
vector<int>ar(k);
pair<int,int>store[nums.size()];int i=0;
for(auto it=map1.begin();it!=map1.end();it++){
store[i].first=it->first;
store[i].second=it->second;
i++;
}
sort(store,store+nums.size()-1,mycmp);
for(i=0;i<k;i++){
ar[i]=store[i].first;
}
return ar;
}
};
由于没有系统的学过c++对this的理解还不到位,不太明白最后的那一段话,日后再回来看。
参考资料:错误解决方法:error: reference to non-static member function must be called_alex_mist的博客-CSDN博客