This question already has answers here:
Operator< and strict weak ordering

(6个答案)


3年前关闭。




这是代码:
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(并非总是,但有时,当两个元素彼此靠近的mTime时)在Visual Studio 2015中引发无效的比较器断言。代码有什么问题?
c&#43;&#43; - C&#43;&#43;: “invalid comparator”断言-LMLPHP

最佳答案

|| p1.mMoney <= p2.mMoney应该为|| ((p1.mTime == p2.mTime) && (p1.mMoney < p2.mMoney)),否则,如果p1.mTime大于p2.mTimep1.mMoney小于p2.Money,则比较将是错误的。确保此类多场比较器满足严格的弱排序要求的一个好习惯是针对所有可能的lt / gt场组合编写测试。

关于c++ - C++: “invalid comparator”断言,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45966807/

10-11 16:45