用C使用堆排序排序日期++(闭合)

问题描述 投票:-1回答:2

我已经做了在使用堆排序排序整数部分。但我很努力在构建逻辑排序日期。

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

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

我怎样才能做到这一点在C ++中使用堆排序?

c++ algorithm sorting c++11 heapsort
2个回答
2
投票

作出这样的比较两个日期的功能,

例如

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
    }
}

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


1
投票

根据您的日期的内部结构则需要提供一个比较的方法。如果利用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);
}
© www.soinside.com 2019 - 2024. All rights reserved.