我在 std::sort 的比较函数中遇到严格的弱排序问题。我不明白为什么这会失败。
我有一些嵌套结构:
struct date{
int day = 1;
int month = 1;
int year = 2017;
};
struct hhmmss{
int hours = 1;
int minutes = 1;
int seconds = 1;
};
struct dateAndTime {
date d;
hhmmss t;
};
struct Trade
{
/*
other unrelevant data
*/
dateAndTime timeClosed;
};
std::vector<Trade>
在我的代码中,在某些时候我有一个我想要排序的填充。
我的排序功能:
void sortTradesByDate(std::vector<Trade>& trades){
std::sort(trades.begin(), trades.end(), compareDateAndTime);
}
我的比较功能:
bool compareDateAndTime(const Trade& t1, const Trade& t2){
if (t1.timeClosed.d.year < t2.timeClosed.d.year)
return true;
else if (t1.timeClosed.d.month < t2.timeClosed.d.month)
return true;
else if (t1.timeClosed.d.day < t2.timeClosed.d.day)
return true;
else if (t1.timeClosed.t.hours < t2.timeClosed.t.hours)
return true;
else if (t1.timeClosed.t.minutes < t2.timeClosed.t.minutes)
return true;
else if (t1.timeClosed.t.seconds < t2.timeClosed.t.seconds)
return true;
return false;
}
在运行该函数并进行调试时,我的第一个项目compareDateAndTime()
在其中一个语句(月)上返回 true 后传递给传递。下一项在小时比较时返回 true,但随后我得到“调试断言失败!” 使用“表达式:无效的运算符<”。
做一些谷歌搜索,这与严格的弱排序有关。但是为什么在比较 int 变量时会失败呢?