我目前正在使用c ++进行A *算法实现,但我一直面临着一个我真正不了解的问题。 让我告诉你我的代码:
// This is my object node
// In case the error might have been in here
// I implemented myself the copy constructor,
// because i thought it might have been my error, but it wasn't
struct node
{
node()
{
this->x = 0;
this->y = 0;
this->g = 0;
this->h = 0;
this->f = 0;
this->parent = nullptr;
}
node(const node &b)
{
this->x = b.x;
this->y = b.y;
this->g = b.g;
this->h = b.h;
this->f = b.f;
this->parent = b.parent;
}
node *parent;
int x, y;
float g, h, f;
node operator=(const node &b)
{
this->x = b.x;
this->y = b.y;
this->g = b.g;
this->h = b.h;
this->f = b.f;
this->parent = b.parent;
return *this;
}
bool operator==(const node b) const { return b.x == x && b.y == y; }
bool operator!=(const node b) const { return !(b.x == x && b.y == y); }
};
// Here i find the lowest F score element
auto b = std::min_element (openNodes.begin(), openNodes.end(), compareFScore);
// I deference the previous iterator to get the object
auto curr = *b;
// If it is the solution i was looking for, then return the path
if (curr == end)
return reconstructPath(curr);
// else i add the curr node to the closed nodes
// and remove it from open nodes
closedNodes.push_back(curr);
openNodes.remove(curr);
// Since that last iterator got removed, i simply get it back from closed nodes
auto c = closedNodes.rbegin();
node current;
// Here the error happens.
// a node's parent is simply a pointer to another node
// c contains all information valid, let's say its parent is 0x0002
// the parent of the parent of c being 0x0001
// the 3rd parent being nullptr (0x0000)
current.parent = c->parent;
在最后一行,current.parent = c-> parent,即使c包含所有有效信息并且有一个很好的链式节点列表,影响current.parent = c-> parent创建一个无限列表指向自身的节点。换句话说:
current.parent = c->parent; // Just as described in the code above
// in debug mode, when i get here, current.parent points to 0x0002, which is correct
// BUT current.parent.parent points to 0x0002 too, while it should point to 0x0001
// and current.parent.parent.parent points to 0x0002 aswell, simply making it an infinite chained-list of doom.
// The worst of all is the node c also changed here to become exactly the same as current,
// while the line before it was 100% correct in debug mode.
这不是我第一次使用链式列表,但这肯定是第一次发生这种奇怪的行为。
感谢您的帮助!
答案 0 :(得分:0)
我发现了我的错误,
实际上列表和向量与正常指针混淆(出于某些原因,如果有人可以解释我喜欢学习更多!),那么通过使用shared_ptr而不是任何地方的严格指针(包括在我的对象中),它解决了这个问题。