2015-08-17 47 views
0

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

从我的代码

段:

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计算),我正在寻找合适的解决方案。任何标记?

回答

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() } 

一旦你拥有的东西更容易理解,你可以玩不同的容器,比如它可能会更快保持在这种情况下,一个排序向量。 )

你的代码本身并不存在任何明显的问题,通常性能提升并不是通过优化小循环来克服的,更多的是你如何组织代码。例如,我看到你有很多indirections,那些缓存未命中成本很高。或者,如果您必须始终查找最小元素,则可以将其缓存在另一个结构中,并且始终保持不变。

+0

这可能是一个stuppid问题,但是你是什么意思的indirections? –

+0

我指的是iterator.value(),假设这个方法是一个指向其他结构的指针,但我想它是Qt API的一部分,所以应该没有问题。 –

+0

你写的stl容器不可能以这种方式使用它。那么我应该删除Qhashiterator?并只使用STL容器? –