我正在用c ++实现A *路径查找。我面临的问题与用于结构的指针和引用有关。
在退出for循环后,它遍历openList(向量)并将currentNode设置为具有最小F值的元素,F的类型为int。
当currentNode发生变化时,currentNode分配的for循环中较早的 parent 会被更改
NavigationNode currentNode;
currentNode.x = 1;
currentNode.y = 2;
parent = ¤tNode
如果我将currentNode更新为另一个值
currentNode.x =23;
currentNode.y = 1;
父母也会改变。我知道父节点正在保存currentNode的地址。所以任何变化都会得到反映但我想知道如何让父值不被改变。如果我以后更新currentNode
我有一个声明为
的结构struct NavigationNode{
int x, y;
float f, g, h;
int value;
NavigationNode *parent;
};
我创建了一个NavigationNode的startNode
NavigationNode startNode;
startNode.x = START_X;
startNode.y = START_Y;
startNode.g = 0;
startNode.f = 0;
我将其插入名为openList
的矢量中vector<NavigationNode> openList;
openList.push_back(startNode);
NavigationNode currentNode;
然后我开始寻找路径
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);
}
}
答案 0 :(得分:1)
currentNode更改反映在父级中的原因是因为我将地址分配给父级。所以任何变化都会得到反映但是,现在我创建currentNode,作为指针,它将具有不同的地址。并且已经将其余部分声明为指针
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