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?

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);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With