【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].

 1 /**
 2  * Definition for an interval.
 3  * struct Interval {
 4  *     int start;
 5  *     int end;
 6  *     Interval() : start(0), end(0) {}
 7  *     Interval(int s, int e) : start(s), end(e) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<Interval> merge(vector<Interval>& ins) {
13         if (ins.empty()) 
14             return vector<Interval>{};
15         vector<Interval> res;
16         sort(ins.begin(), ins.end(), [](Interval a, Interval b){return a.start < b.start;});
17         res.push_back(ins[0]);
18         
19         for (int i = 1; i < ins.size(); i++) {
20             if (res.back().end < ins[i].start)
21                 res.push_back(ins[i]);
22             else
23                 res.back().end = max(res.back().end, ins[i].end);
24         }
25         return res;
26     }
27 };

  函数写法:

 1 /**
 2  * Definition for an interval.
 3  * struct Interval {
 4  *     int start;
 5  *     int end;
 6  *     Interval() : start(0), end(0) {}
 7  *     Interval(int s, int e) : start(s), end(e) {}
 8  * };
 9  */
10 bool mySort(const Interval &a, const Interval &b) {
11     return a.start < b.start;
12 }
13 class Solution {
14 public:
15     vector<Interval> merge(vector<Interval>& ins) {
16         if (ins.empty()) 
17             return vector<Interval>{};
18         vector<Interval> res;
19         sort(ins.begin(), ins.end(), mySort);
20         res.push_back(ins[0]);
21         
22         for (int i = 1; i < ins.size(); i++) {
23             if (res.back().end < ins[i].start)
24                 res.push_back(ins[i]);
25             else
26                 res.back().end = max(res.back().end, ins[i].end);
27         }
28         return res;
29     }
30 };

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

  std::sort要求函数对象,或是静态/全局函数指针,非静态成员函数指针不能直接传递给std::sort
 
 
posted @ 2018-03-15 22:04  Vincent丶丶  阅读(6999)  评论(0编辑  收藏  举报