如何在 C++ 中有效比较两个日期时间结构?

Maf*_*Maf 1 c++ datetime struct timestamp

我有以下日期时间结构:

struct DateTime
{
    std::uint16_t year;
    std::uint8_t month;
    std::uint8_t day;
    std::uint8_t hour;
    std::uint8_t minute;
    std::uint8_t second;
    std::uint16_t milisecond;
};
Run Code Online (Sandbox Code Playgroud)

我的疑问是关于LessThanGreaterThan方法。为了避免一堆ifselses ,我已经实现如下,但我可能没有涵盖所有可能的情况:

bool GreaterThan(const DateTime& datetime)
{
    bool greater{true};

    // When found a different value for the most significant value, the evaluation is interrupted
    if ((year <= datetime.year) && (month <= datetime.month || year < datetime.year) &&
        (day <= datetime.day || month < datetime.month) && (hour <= datetime.hour || day < datetime.day) &&
        (minute <= datetime.minute || hour < datetime.hour) &&
        (second <= datetime.second || minute < datetime.minute) &&
        (milisecond <= datetime.milisecond || second < datetime.second))
    {
        greater = false;
    }

    return greater;
}

bool LessThan(const DateTime& datetime)
{
    bool less{true};

    // When found a different value for the most significant value, the evaluation is interrupted
    if ((year >= datetime.year) && (month >= datetime.month || year > datetime.year) &&
        (day >= datetime.day || month > datetime.month) && (hour >= datetime.hour || day > datetime.day) &&
        (minute >= datetime.minute || hour > datetime.hour) &&
        (second >= datetime.second || minute > datetime.minute) &&
        (milisecond >= datetime.milisecond || second > datetime.second))
    {
        less = false;
    }

    return less;
}
Run Code Online (Sandbox Code Playgroud)

请告诉我哪些可能的情况不包括在内。

Rya*_*ang 7

您的实施看起来过于痛苦。有一种更简单、更合乎逻辑的方法可以实现这一目标。如果您了解贪婪算法,它的思维过程与此类似。

bool GreaterThan(const datetime& datetime)
{
    if(year != datetime.year) return year > datetime.year;
    if(month != datetime.month) return month > datetime.month;
    //... and so on (omitted)
    return false; // they are the same
}
Run Code Online (Sandbox Code Playgroud)

您可以LessThan类似地实施。

  • [`std::tie`](https://en.cppreference.com/w/cpp/utility/tuple/tie) 将为您完成这一切,请参阅上面的评论。 (4认同)
  • `std::make_tuple` 将复制,`std::tie` 创建一个引用元组。 (4认同)
  • @RichardCritten 哦,哇。我不知道`std::tie`。哇,我在我的编程生涯中一直在缓慢地写它...... (2认同)