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
     
     
  • 相关阅读:
    如何使用phantomJS来模拟一个HTML元素的鼠标悬停
    nodejs中使用cheerio爬取并解析html网页
    Node.js 动态网页爬取 PhantomJS 使用入门(转)
    一口一口吃掉Hibernate(五)——一对多单向关联映射
    开源 免费 java CMS
    [WinForm]dataGridView导出到EXCEL
    关键帧和动画
    uva 696
    uva 11181
    IE下target获得焦点时存在虚线的问题
  • 原文地址:https://www.cnblogs.com/Atanisi/p/8576679.html
Copyright © 2011-2022 走看看