0
현재 C++의 A * 알고리즘 구현을하고 있지만 실제로 이해하지 못하는 문제에 직면 해 있습니다. 내가 당신에게 내 코드를 보여 드리죠 : 그 마지막 줄, current.parent = C-> 부모에chained 노드의 부모 포인터 목록이 올바르게 작동하지 않습니다. C++
// 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;
를, C는 모든 유효한 정보를 포함하고 노드의 좋은 체인-목록에서 허식 전류를 경우에도 마찬가지입니다. 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.
처음에는 연결 목록으로 작업하지 않지만이 이상한 동작이 발생하는 것은 처음입니다.
도움 주셔서 감사합니다. 내 오류를 발견
openNodes 및 closedNodes는이 아니고 인 목록입니다. –
Scriptodude
참조 된 코드 중 일부를 포함하지 않았기 때문에 약간 명확하지 않습니다. 그러나, 내 생각 엔 당신이 노드를 복사하고 있다는 것을 의미하지 않을 때'push_back'과 같은 일을 할 때 노드를 복사하고 나서 복사본이 아닌 원본을 계속 수정하는 것입니다. 또한, C++ 11 인 경우 관련이 없으며'std :: shared_ptr'을 사용하여이 포인터를 사용하지 마십시오. – aruisdante
복사 생성자와 대입 연산자는 기본값을 복제합니다 (대입 연산자에서 반환 값을 잘못받는 것과는 별개로). 전체 수업을 다음과 같이 단순화 할 수 있습니다. http://ideone.com/whwtaE – kfsone