如何比较数组以及为何错误的排序规则导致崩溃

我在开发中写出一个崩溃的代码,当使用 std::sort 排序时,没有定义严格弱序的 operator< ,导致了崩溃。

排序比较的是一个数组,起初的写法是:

// 错误的写法
bool operator<(const Foo &rhs) const
{
    for (int i = 0; i < LEN; ++i)
    {
        if (lhs.item_list[i] < rhs.item_list[i])
        {
            return true;
        }

        return lhs.key < rhs.key;
    }
}

问题出在上述比较不是严格弱序的,lhs的一个数组元素可能小于rhs的,同时rhs的一个数组元素也可能小于lhs的,那么lhs可以小于rhs,也可以大于rhs,这就引发了排序算法的崩溃。

正确的方法应该是参考 string 的方式,比较第一个不同的元素。即:

bool operator<(const Foo &rhs) const
{
    for (int i = 0; i < LEN; ++i)
    {
        if (lhs.item_list[i] != rhs.item_list[i])
        {
            return lhs.item_list[i] < rhs.item_list[i];
        }

        return lhs.key < rhs.key;
    }
}
原文地址:https://www.cnblogs.com/demon90s/p/15565815.html