I'm currently working on an A* algorithm implementation in c++, but i've been facing a problem that I really don't understand. Let me show you my code :
// 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;
on that last line, current.parent = c->parent, even if c contains all valid information and has a nice chained-list of nodes, the affectation current.parent = c->parent creates an infinite list of nodes pointing to itself. In other words :
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.
It isn't my first time working with chained lists, but it sure is the first time this weird behavior happens.
thanks for your help!
Aucun commentaire:
Enregistrer un commentaire