【发布时间】:2018-05-16 12:37:35
【问题描述】:
我在 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 变量时会失败呢?
【问题讨论】:
-
它失败是因为比较器没有实现严格的弱排序比较。您可以通过一些单元测试轻松检查。
-
问题是您同时拥有
d1 < d2和d2 < d1的对象。 -
但为什么有时会失败,有时会通过?它不会总是失败吗?
标签: c++ sorting strict-weak-ordering