【问题标题】:std::sort vector of struct invalid operator<结构无效运算符的 std::sort 向量<
【发布时间】: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&lt;Trade&gt;,我想对其进行排序。

我的排序功能:

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 &lt; d2d2 &lt; d1 的对象。
  • 但为什么有时会失败,有时会通过?它不会总是失败吗?

标签: c++ sorting strict-weak-ordering


【解决方案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

【讨论】:

    【解决方案2】:

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

    考虑这种情况:

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

    compareDateAndTime(t1, t2) 将返回 true

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

    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;
    

    ...等等...

    【讨论】:

    • 像魅力一样工作并且有意义。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2021-02-20
    • 1970-01-01
    • 2011-05-15
    • 1970-01-01
    • 1970-01-01
    • 2016-03-06
    • 1970-01-01
    • 2016-11-17
    相关资源
    最近更新 更多