0

我用 C++ 开发了一个游戏,并希望确保一切都正确完成。使用 QHashIterator 来检查列表中的哪个项目具有最低值(寻路的 F 成本)是否是一个好的解决方案。

我的代码片段:

 while(!pathFound){ //do while path is found

        QHashIterator<int, PathFinding*> iterator(openList);
        PathFinding* parent;
        iterator.next();
        parent = iterator.value();

        while(iterator.hasNext()){ //we take the next tile, and we take the one with the lowest value
            iterator.next();
            //checking lowest f value
            if((iterator.value()->getGcost() + iterator.value()->getHcost()) < (parent->getGcost() + parent->getHcost())){
                parent = iterator.value();
            }
        }

        if(!atDestionation(parent,endPoint)){ //here we check if we are at the destionation. if we are we return our pathcost.
            clearLists(parent);
            filllists(parent,endPoint);
        }else{
            pathFound = true;
            while(parent->hasParent()){
                 mylist.append(parent);
                 parent = parent->getParent();
            }
            pathcost = calculatePathCost(mylist);    //we calculate what the pathcost is and return it
        }
     }

如果不?有更好的改进吗?

我还发现了一些关于 std::priority_queue 的信息。它比 QHashIterator 更好吗?

对于那些不大的游戏世界来说,这可能不是问题。但是,当游戏世界很大时(例如 + 10000 次计算),我正在寻找合适的解决方案。任何标记?

4

1 回答 1

1

在这里,您基本上扫描整个地图以根据某些值找到最小的元素:

while(iterator.hasNext()){ //we take the next tile, and we take the one with the lowest value
    iterator.next();
    //checking lowest f value
    if((iterator.value()->getGcost() + iterator.value()->getHcost()) < (parent->getGcost() + parent->getHcost())){
        parent = iterator.value();
    }
}

所有这些代码,如果你有一个 stl 容器,例如一个地图,可以简化为:

auto parent = std::min_element(iterator.begin(), iterator.end(), [](auto& lhs, auto& rhs)
  { lhs.value()->getGcost() + lhs.value()->getHcost()) < (rhs.value()->getGcost() + rhs.value()->getHcost() }

一旦你有了更容易理解的东西,你就可以使用不同的容器,例如在这种情况下保存一个排序的向量可能会更快。)

您的代码本身并没有出现任何明显的问题,通常优化小循环并不能克服性能提升,更多的是您的代码是如何组织的。例如,我看到您有很多间接寻址,这些间接寻址在缓存未命中方面付出了很多代价。或者,如果您必须始终找到最小元素,您可以将其缓存在另一个结构中,并且您将始终在一个恒定的时间拥有它。

于 2015-08-17T15:48:38.233 回答