gpt4 book ai didi

c++ - std::sort 将元素与 null 进行比较

转载 作者:可可西里 更新时间:2023-11-01 18:20:10 26 4
gpt4 key购买 nike

我有以下排序算法,它对唯一 armor_set 指针的 std::vector 进行排序。根据我的排序算法的某些属性,它会阻塞并遇到未定义的行为,最终将有效的 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;
}
});

最佳答案

比较函数必须遵循严格的弱排序。

比如我是sort函数,给你两个armor_set指针,问你“哪个先到?”并且您返回一个真/假值,表示哪个值先出现。然后我给你同样的两个 armor_set 指针,但这次,改变项目的顺序。我问你同样的问题“哪个先来?”。然后返回相同的 true/false 值。你猜怎么着——你输了。

简而言之,这违反了严格的弱排序。没办法a < b ,同时b < a .看看你有点复杂的比较功能,我猜你违反了这条规则。

如果您使用的是 Visual Studio,调试运行时会像这样精确检查顺序违规。比较函数被调用了两次,第一次是A,B顺序,第二次是B,A顺序。比较每个调用的返回值,如果有违规,将发生 assert()。

关于c++ - std::sort 将元素与 null 进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21842749/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com