【C++】标准库sort函数的自定义排序

时间:2023-03-09 08:30:26
【C++】标准库sort函数的自定义排序

  自定义排序需要单独写一个compare函数

例1 LeetCode 056. Merge Intervals

Given a collection of intervals, merge all overlapping intervals.

For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].

 /**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
class Solution {
public:
vector<Interval> merge(vector<Interval>& ins) {
if (ins.empty())
return vector<Interval>{};
vector<Interval> res;
sort(ins.begin(), ins.end(), [](Interval a, Interval b){return a.start < b.start;});
res.push_back(ins[]); for (int i = ; i < ins.size(); i++) {
if (res.back().end < ins[i].start)
res.push_back(ins[i]);
else
res.back().end = max(res.back().end, ins[i].end);
}
return res;
}
};

  函数写法:

 /**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
bool mySort(const Interval &a, const Interval &b) {
return a.start < b.start;
}
class Solution {
public:
vector<Interval> merge(vector<Interval>& ins) {
if (ins.empty())
return vector<Interval>{};
vector<Interval> res;
sort(ins.begin(), ins.end(), mySort);
res.push_back(ins[]); for (int i = ; i < ins.size(); i++) {
if (res.back().end < ins[i].start)
res.push_back(ins[i]);
else
res.back().end = max(res.back().end, ins[i].end);
}
return res;
}
};

  注意到compare函数写在类外,这是因为

  std::sort要求函数对象,或是静态/全局函数指针,非静态成员函数指针不能直接传递给std::sort