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