【发布时间】:2016-07-24 23:47:45
【问题描述】:
我正在实现A* 最短路径算法。 Openlist 部分存储将要访问的所有节点。该列表就像一个优先队列,第一个元素具有最小的成本值,因此在每次迭代中,我们只需弹出第一个元素并访问它。但是在迭代中,我们需要遍历这个节点的邻居并检查邻居是否在 Openlist 中。
也就是说这个Openlist需要支持两种操作:
- 自动分拣
- 查找节点(通过其 ID)
这里的问题是Openlist会按照cost值排序,而查找需要根据邻居节点的ID(相邻节点)。所以我正在考虑使用集合,其中元素是节点。但是我不知道如何在这个集合中通过它的 ID 来查找一个元素。
struct astar_node
{
string id;
double f; //estimated cost;
double g; //distance from source to this node;
double h; //heuristic cost from this node to target;
};
struct openlist_compare
{
bool operator()(const astar_node &node1, const astar_node &node2 ){
return node1.f < node2.f ;
}
};
std::set<astar_node, openlist_compare> Openlist;
【问题讨论】:
-
保留两套,一套由
f索引,另一套由id索引。 -
您不会在集合中通过其 ID 来查找元素 - 至少在不遍历整个集合的情况下是这样。这不是套装的用途。
-
@但是 set 的 find() 方法有什么作用呢?
-
@daydayup 给你一个指向集合中元素的迭代器?
-
@daydayup 你必须搜索它。一个集合只索引一个值。
std:: find_if(OpenList.begin(), OpenList.end(), [wantId](const astar_node& node){ return node.id == wantId; }