std :: sort将元素比较为null

Col*_*ett 7 c++ sorting algorithm c++11

我有以下排序算法,它排序一个std::vector独特的armor_set指针.通过我的排序算法的某些属性,它闷死了起来,跑进这最终比较有效的未定义行为lhsrhs这是一个nullptr.

尽管多次移动算法,但我一直无法辨别问题.我觉得好像我错过了一些关于这个std::sort算法如何工作的简单规则.

任何帮助,将不胜感激.

std::vector<armor_set*> armor_sets;

//insertion of unique armor sets here

std::sort(armor_sets.begin(), armor_sets.end(), [](armor_set* lhs, armor_set* rhs)
{
    auto lhs_collectible_count = collectible_mgr::get().count(lhs->needed_collectible);
    auto rhs_collectible_count = collectible_mgr::get().count(rhs->needed_collectible);

    if(lhs_collectible_count > 0 && rhs_collectible_count == 0)
    {
        return true;
    }
    else if(lhs_collectible_count == rhs_collectible_count)
    {
        return lhs->sort_index > rhs->sort_index;
    }
    else
    {
        auto lhs_collectibles_needed_count = lhs_collectible_count - lhs->collectibles_needed;
        auto rhs_collectibles_needed_count = rhs_collectible_count - rhs->collectibles_needed;

        return lhs_collectibles_needed_count > rhs_collectibles_needed_count;
    }
});
Run Code Online (Sandbox Code Playgroud)

Pau*_*zie 11

比较函数必须遵循严格弱顺序.

例如,如果我是排序函数,我给你两个armor_set指针,问你"哪一个先来?" 并返回一个表示哪个值最先出现的真/假值.然后我给你相同的两个armor_set指针,但这次,改变项目的顺序.我问你同样的问题"哪个先来?".然后返回相同的true/false值.猜猜是什么 - 你失败了.

简而言之,这违反了严格的弱序.没有办法a < b,同时也是如此b < a.看看你有点复杂的比较函数,我的猜测是你违反了这条规则.

如果您使用的是Visual Studio,则调试运行时会对此类订单违规进行精确检查.比较函数被调用两次,第一次使用A,B顺序,第二次使用B,A顺序.比较每个调用的返回值,如果存在违规,则会发生assert().