zoukankan      html  css  js  c++  java
  • 【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
     
     
  • 相关阅读:
    宋体、新宋体、仿宋体
    单例模式————你就是我的唯一
    极乐净土代码——第一辑
    泛函是个什么概念
    http和https的区别
    get和post的区别
    浏览器输入URL按回车后都经历了什么?
    求两个列表的交集、并集、差集
    使用lamdba函数对list排序
    乐观锁和悲观锁的区别
  • 原文地址:https://www.cnblogs.com/Atanisi/p/8576679.html
Copyright © 2011-2022 走看看