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)
我的疑问是关于LessThan和GreaterThan方法。为了避免一堆ifs和elses ,我已经实现如下,但我可能没有涵盖所有可能的情况:
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)
请告诉我哪些可能的情况不包括在内。
您的实施看起来过于痛苦。有一种更简单、更合乎逻辑的方法可以实现这一目标。如果您了解贪婪算法,它的思维过程与此类似。
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类似地实施。