1

我在 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 变量时会失败呢?

4

2 回答 2

2

您的比较函数没有实现严格的弱排序

考虑这种情况:

  • t1:年=2017,月=2
  • t2:年=2016,月=5

compareDateAndTime(t1, t2)会回来true的。

您应该继续比较month当且仅当year相同时。

if (t1.timeClosed.d.year < t2.timeClosed.d.year)
    return true;
if (t1.timeClosed.d.year > t2.timeClosed.d.year)
    return false;
if (t1.timeClosed.d.month < t2.timeClosed.d.month)
    return true;
if (t1.timeClosed.d.month > t2.timeClosed.d.month)
    return false;

……等等……

于 2017-12-02T16:15:23.347 回答
1

利用标准库的好方法:

return std::tie(t1.timeClosed.d.year, t1.timeClosed.d.month) < std::tie(t2.timeClosed.d.year, t2.timeClosed.d.month);

您可以在 std::tie 中添加缺少的成员(它是一个可变参数模板)。这使用了 std::tuple 的 operator<,它被定义为你所期望的。

于 2017-12-02T16:38:22.217 回答