【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
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM