Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: “invalid comparator” assert [duplicate]

Tags:

c++

c++11

stl

Here is the code:

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);

std::sort (not always, but sometimes, when mTime of two elements close to each other) raises invalid comparator assert in Visual Studio 2015. What's wrong with the code?
enter image description here

like image 668
deko Avatar asked Dec 06 '25 09:12

deko


1 Answers

The problem is with the implementation of sortP. It does not satisfy the strictly weak ordering criteria. Read the details at https://www.boost.org/sgi/stl/StrictWeakOrdering.html.

I suggest the following change:

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 <=
};

You can use std::tie to make the implementation simpler.

auto sortP = [](const Payment& p1, const Payment& p2)
{
   return std::tie(p1.mTime, p1.mMoney) < std::tie(p2.mTime, p2.mMoney);
};
like image 180
R Sahu Avatar answered Dec 08 '25 08:12

R Sahu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!