本文主要是介绍比较器与类的成员函数(2019.10.22),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
关键:函数后面的const可以认为是用作修饰this指针
1.当把比较器不作为类的成员函数,因为const是用来修饰this指针的,那么必须有类,所以函数后面不能加const
bool cmp(const Interval &a,const Interval &b){//后面不加constif(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函数,并且后面不加constvector<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;}
};
这篇关于比较器与类的成员函数(2019.10.22)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!