【问题标题】:Sort Dates using HeapSort in C++ [closed]在 C++ 中使用 HeapSort 对日期进行排序 [关闭]
【发布时间】:2019-02-10 15:21:26
【问题描述】:

我已经完成了使用 heapsort 对整数进行排序的部分。但我正在努力建立对日期进行排序的逻辑。

例如:1956 年 2 月 22 日、1856 年 3 月 24 日、1856 年 3 月 22 日。

我需要的输出是:1856 年 3 月 22 日,1856 年 3 月 24 日,1956 年 2 月 22 日。

如何在 c++ 中使用 heapsort 做到这一点?

【问题讨论】:

  • 将日期转换为整数(例如,将 February 22 1956 表示为 19560222),对它们进行排序,然后转换回来。
  • 谢谢,明白逻辑

标签: c++ algorithm sorting c++11 heapsort


【解决方案1】:

制作一个比较两个日期的函数,

例如

bool dateCompare(Date d1, Date d2) {
    if(d1.year>d2.year) return true; //d1 is sooner
    else if(d2.year>d1.year) return false; //d2 is sooner
    else {
        //the years are equal, compare months the same way
    }
}

或将日期转换为整数并对其进行排序

【讨论】:

    【解决方案2】:

    根据您的日期在内部的结构方式,您需要提供一个比较方法。如果使用 STL,比较看起来像:

    struct Date {
      int year;
      int month;
      int day;
    };
    bool operator<(Date const& lhs, Date const& rhs) {
        return std::tie(lhs.year, lhs.month, lhs.day)
             < std::tie(rhs.year, rhs.month, rhs.day);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-27
      • 2021-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-29
      • 2015-04-01
      • 2015-12-09
      相关资源
      最近更新 更多