C++:“无效比较器”断言

dek*_*eko 1 c++ stl c++11

这是代码:

struct Payment
{
    Payment(time_t time, float money) : mTime(time), mMoney(money) {}
    bool operator==(const Payment& p) const // exact comparison
    {
        return mTime == p.mTime && mMoney == p.mMoney;
    }
    time_t  mTime;
    float   mMoney;
};

std::vector<Payment>    payments;

auto sortP = [](const Payment& p1, const Payment& p2) { return p1.mTime < p2.mTime || p1.mMoney <= p2.mMoney; };
std::sort(payments.begin(), payments.end(), sortP);
Run Code Online (Sandbox Code Playgroud)

std::sort(并非总是如此,但有时,当mTime两个元素彼此靠近时)在 Visual Studio 2015 中引发无效比较器断言。代码有什么问题?
在此处输入图片说明

R S*_*ahu 5

问题在于sortP. 它不满足严格的弱排序标准。在http://www.sgi.com/tech/stl/StrictWeakOrdering.html阅读详细信息。

我建议进行以下更改:

auto sortP = [](const Payment& p1, const Payment& p2)
{
   // Order by mTime if they are not equal.
   if ( p1.mTime != p2.mTime)
   {
     return p1.mTime < p2.mTime;
   }

   // Otherwise, order by pMoney
   return ( p1.mMoney < p2.mMoney); // Use < not <=
};
Run Code Online (Sandbox Code Playgroud)

您可以使用std::tie使实现更简单。

auto sortP = [](const Payment& p1, const Payment& p2)
{
   return std::tie(p1.mTime, p1.mMoney) < std::tie(p2.mTime, p2.mMoney);
};
Run Code Online (Sandbox Code Playgroud)

  • 使用 `std::tie` 更简单 (3认同)