std::sort 错误"Expression : invalid operator <"

解决:std::sort的比较函数,切记仅使用小于或大于,不要使用小于等于或大于等于。即所谓的“ strict weak ordering”,也就是说,如果a==b,则返回的应该是false,如果返回的是true,则会出上面的错

这个问题是标准库sort实现导致的

参考https://blog.csdn.net/qq_35097289/article/details/104648601

 

class testOperator
{
public:
    

    int value=0;
    int value2=0;
    void setV(int v)
    {
        value = v;
    }
    void setV2(int v2)
    {
        value2 = v2;
    }

    bool operator <=(const testOperator& other) const
    {
        if (other < *this)
        {
            return false;
        }
        return true;
    }

    bool operator <(const testOperator& other) const
    {
        if (this->value == other.value)
        {
            return this->value2 < other.value2;
        }
        return this->value < other.value;
    }
};

bool compareTestOperator(const testOperator& t1, const testOperator& t2)
{
    return t1 <= t2;  //不能使用<=,如果容器元素中有相等的,就会导致crash
}

int main() {

    {
        testOperator t1;
        testOperator t2;
        t2.setV(10);//当前没问题,注释掉这一句就会crash

        std::vector < testOperator > vec = {t1, t2};
        std::sort(vec.begin(), vec.end(),compareTestOperator);
        std::cout << vec.size() << std::endl;
    }

 

posted @ 2024-03-26 20:34  乐swap火  阅读(2)  评论(0编辑  收藏  举报