私は C++ の完全な初心者で、今まですべて順調に進んでいます。私はポインターのアイデアに慣れていません(私はpythonから来ました)、この奇妙なエラーがあります。
基本的に、私はこの「SearchNode」クラスを作成しました。以下は、ナイト (チェス盤) が現在の状態から移動できる可能性のあるセルを表す、他の SearchNode インスタンスのベクトルを返す必要があるメソッド「getChildren」の 1 つです。(BFS)
そうは言っても、ベクターへのプッシュを終了すると、すべての要素が突然最初の要素のみを指します。誰かがここで私を助けてくれますか?
PS: c++ push_back が想定どおりに機能しないのと同様の問題ですが、Angela (自分でコンパイラを作成していた) とは異なり、私は c++ の初心者です。どうぞよろしくお願いいたします。
アップデート
int* を取り除き、状態に配列を使用しました。グラフを正常に検索し (したがって、状態は問題ありません)、最短経路を見つけることができましたが、経路を再構築することはできなかったようです。
テストするために、{0,0} から始めて {4,4} を見つけることができましたが、getPath メソッドによるパスは {4,4}、{3,6}、{3,6}、{3 でした。 ,6} ... ({3,6} の無限ループ)。親ポインターまたは getPath 関数に何か問題がありますか? 事前にご支援いただきありがとうございます。
//Search class
class SearchNode
{
public:
//Variables
SearchNode *m_parent;
array<int,2> m_state; //I don't understand typedef's yet, will use them when I'm clearer with them :)
//Normal Constructor
SearchNode(array<int,2>& state_, SearchNode *parent_=nullptr) :
m_state(state_),
m_parent(parent_)
{}
//Method to get Next reachable states. Returns instances of SearchNode.
vector<SearchNode> getChildren()
{
int legalMoves[8][2] = {{1,2},{1,-2},{-1,2},{-1,-2},{2,1},{2,-1},{-2,1},{-2,-1}};
vector<SearchNode> children;
children.reserve(8);
for(int i=0; i<8; i++)
{
int x = (m_state[0] + legalMoves[i][0]);
int y = (m_state[1] + legalMoves[i][1]);
if( (x>-1) and (x<9) and (y<9) and (y>-1)) // Within the bounds of the board
{
array<int,2> childState = {x,y};
SearchNode childNode = SearchNode(childState,this);
children.push_back(childNode);
}
}
return children;
}
void getPath()
{
cout<<"\nPath: ";
cout<< this->print();
SearchNode current = *this;
unsigned int counter = 1;
while((current.m_parent!=nullptr) and counter< 10)
{
counter++;
cout<< (current.m_parent)->print();
current = *(current.m_parent);
}
cout << (current.m_parent)->print();
}
string print()
{
stringstream out;
out << "{" << this->m_state[0] << "," << this->m_state[1] << "} ";
return out.str();
}
};