在刷leetcode时遇到错误:
这是因为我在类成员函数中调用三个参数的sort(),并且也将cmp函数定义为类成员函数,需要将cmp函数在类中定义为static!
代码如下:
class Solution {
public:
static bool cmp(vector<int>& a,vector<int>& b){
//bool cmp(vector<int>& a,vector<int>& b) 错误
if(b[1] == a[1])
return a[0]<b[0];
else
return a[1]<b[1];
}
vector<vector<int>> merge(vector<vector<int>>& intervals) {
stack<vector<int>> s;
sort(intervals.begin(),intervals.end(),cmp);
for(int i=intervals.size()-1;i>=0;i--){
if(!s.empty()){
if(intervals[i][1]<s.top()[0])
s.push(intervals[i]);
else{
int left = min(intervals[i][0],s.top()[0]);
int right = max(intervals[i][1],s.top()[1]);
s.pop();
s.push({left,right});
}
}
else
s.push(intervals[i]);
}
vector<vector<int>> res;
while(!s.empty()){
res.push_back(s.top());
s.pop();
}
return res;
}
};
为什么cmp函数在作为类成员函数的时候一定需要static修饰呢?这是因为所有我们在类内定义的非static成员函数在经过编译后隐式的为他们添加了一个this指针参数!变为了:
bool cmp(Solution *this, int a, int b)
而标准库的sort()函数的第三个cmp函数指针参数中并没有这样this指针参数,因此会出现输入的cmp参数和sort()要求的参数不匹配,从而导致了:
error: reference to non-static member function must be called
而我们知道static静态类成员函数是不需要this指针的,因此改为静态成员函数即可通过!