关键:函数后面的const可以认为是用作修饰this指针
1.当把比较器不作为类的成员函数,因为const是用来修饰this指针的,那么必须有类,所以函数后面不能加const
bool cmp(const Interval &a,const Interval &b){//后面不加const
if(a.start!=b.start) return a.start<b.start;
else return a.end<b.end;
}
class Solution {
public:
vector<Interval> merge(vector<Interval> &intervals) {
vector<Interval> ans;
int sz=intervals.size();
sort(intervals.begin(),intervals.end(),cmp);
for(int i=0;i<sz;){
auto cur=intervals[i];
while(++i<sz){
auto nxt=intervals[i];
if(nxt.start<=cur.end) cur.end=max(cur.end,nxt.end);
else break;
}
ans.push_back(cur);
}
return ans;
}
};
2.当把比较器作为类的成员函数,还是那句话,因为const是修饰this指针,我们需要将其作为static成员函数
class Solution {
public:
static bool cmp(const Interval &a,const Interval &b){
if(a.start!=b.start) return a.start<b.start;
else return a.end<b.end;
}//定义为static函数,并且后面不加const
vector<Interval> merge(vector<Interval> &intervals) {
vector<Interval> ans;
int sz=intervals.size();
sort(intervals.begin(),intervals.end(),cmp);
for(int i=0;i<sz;){
auto cur=intervals[i];
while(++i<sz){
auto nxt=intervals[i];
if(nxt.start<=cur.end) cur.end=max(cur.end,nxt.end);
else break;
}
ans.push_back(cur);
}
return ans;
}
};