对象和静态位置之间的堆对比

时间:2016-11-19 01:31:50

标签: c++ heap a-star comparison-operators

我正在寻找2D平铺游戏的寻路。我找到了this similar answer,但我不确定如何heap compares i <> i+i创建比较运算符,当i need manhattan(i) <> manhattan(i+1)?我疯狂地生成cpp时对我很轻松。

typedef std::tuple<int, int> coord;

int manhattan(coord start, coord goal){
    return (std::abs(start.get<0> - goal.get<0>) + \ 
            std::abs(start.get<1> - goal.get<1>) )
}

bool operator()((const coord& left, const coord& right){
   return manhattan(left, ???) < manhattan(right, ???);    
}

vector pathfinding(coord start, coord goal){
  //using A* format
  vector<coord> open;

  while(open){
      //how can I compare indexes to goal parameter?
      std::sort_heap(open.begin(), open.end()); 

      current = open.front();
  }

}

1 个答案:

答案 0 :(得分:1)

我建议使用lambda functionvector pathfinding(coord start, coord goal) { // using A* format vector<coord> open; auto comp = [&goal](const coord& lhs, const coord& rhs) { return manhattan(lhs, goal) > manhattan(rhs, goal); // greater-than, for a min-heap }; while(open){ std::sort_heap(open.begin(), open.end(), comp); ... } } 的每次调用创建一个本地比较器。另外,不要忘记将其传递给std::sort_heap。试试这个:

comp

[&goal]被初始化为lambda对象(如Python中的lambda或JavaScript中的匿名函数)。 goal部分意味着通过引用“捕获”goal变量以在lambda中使用。它就像一个自定义类,其成员变量存储对operator()的引用,并且coord使用goal比较两个std::sort_heap

此外,我认为您不应该使用std::make_heap ...使用std::push_heapstd::pop_heap(请参阅链接文档中的example)。我们的想法是在开始时调用push/pop_heap一次,并在添加/删除时使用// to push "direction" onto the heap: open.push_back(direction); std::push_heap(open.begin(), open.end(), comp); // to pop "current" off of the heap: std::pop_heap(open.begin(), open.end(), comp); current = open.pop_back(); 来维护堆。无需每次迭代对其进行排序。例如:

{{1}}