I am implementing A* path finding in c++. The issue which I am facing is related with pointers and references being used with structures.
After it exits the for loop, it traverses the openList (vector) and sets the currentNode to the element with the least F value, F is of type int.
When the currentNode gets changed, the parent which was earlier in the for loop assigned by the currentNode, gets changed
NavigationNode currentNode;
currentNode.x = 1;
currentNode.y = 2;
parent = ¤tNode
if I update the currentNode to another value
currentNode.x =23;
currentNode.y = 1;
the parent will also get changed. I understand that parent is holding the address of currentNode. so any changes get reflected. But I want to know how can I make the parent value not to be changed. if I later update the currentNode
I have a struct declared as
struct NavigationNode{
int x, y;
float f, g, h;
int value;
NavigationNode *parent;
};
I create a startNode of NavigationNode
NavigationNode startNode;
startNode.x = START_X;
startNode.y = START_Y;
startNode.g = 0;
startNode.f = 0;
I inserted it into vector named openList
vector<NavigationNode> openList;
openList.push_back(startNode);
NavigationNode currentNode;
Then I start the finding the path
while (!openList.empty())
{
for (auto i = openList.begin(); i != openList.end(); ++i)
{
if (i == openList.begin() || (*i).f <= currentNode.f)
{
currentNode = (*i);
}
}
for (int i = 0; i < 8; i++)
{
NavigationNode nextNode;
nextNode.x = xChange;
nextNode.y = yChange;
// some logic operations
// assign the currentNode to the parentNode
nextNode.parent = ¤tNode;
nextNode.value = map[xChange][yChange];
openList.push_back(nextNode);
}
}
The reason why currentNode changes get reflected in parent, is because I am assigning the address to parent. so any changes get reflected. However, now I create currentNode, as a pointer, it will have different address. and have declared the rest as pointers as well
NavigationNode *startNode;
startNode->x = START_X;
startNode->y = START_Y;
startNode->g = 0;
startNode->f = 0;
vector<NavigationNode*> openList;
openList.push_back(*startNode);
NavigationNode *currentNode = new NavigationNode;
while (!openList.empty())
{
// sort the vector by increasing F values, so the lowest F values will be at the first location
// sort(openList.begin(), openList.end(), compareByF);
for (auto i = openList.begin(); i != openList.end(); ++i){
if (i == openList.begin() || (*i)->f <= currentNode->f){
currentNode = (*i);
}
}
for (int i = 0; i < numberOfDirections; i++)
{
NavigationNode *nextNode = new NavigationNode;
nextNode->x = xChange;
nextNode->y = yChange;
// some logic operations
// assign the currentNode to the parentNode
nextNode->parent = currentNode;
nextNode->value = map[xChange][yChange];
openList.push_back(nextNode);
} // end for loop
}// end while loop