报错代码
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Sol{
public:
bool cmp(int a,int b){ return a < b; }
void mysort(vector<int>& a){
sort(a.begin(),a.end(),cmp);
}
};
int main(){
Sol trial;
vector<int> a = {1,4,5,9,2};
trial.mysort(a);
for (auto i: a) cout << i << ' ';
return 0;
}
报错
reference to non-static member function must be called
或
no matching function for call to xxx
原因
class中函数参数隐藏了this指针,实际上cmp的参数有3个而非2个,不符合sort函数的期望。
解决方案
1.将比较函数cmp声明为静态的:
class Sol{
public:
static bool cmp(int a,int b){ return a < b; }
void mysort(vector<int>& a){
sort(a.begin(),a.end(),cmp);
}
};
2.将比较函数cmp移出class:
bool cmp(int a,int b){ return a < b; }
class Sol{
public:
void mysort(vector<int>& a){
sort(a.begin(),a.end(),cmp);
}
};
问题得到解决