0
これはリンク・リストを作成するために使用するコードです。ベクトル・イテレータの値を取得しようとするとバス・エラーが発生する
struct Node
{
int data;
struct Node *next;
};
Node* buildList(vector<int> &useThisVectorToBuildList)
{
Node *newNode, *head, *tail;
// vector<int> populateList(10,2,2,1,2,4,5);
int vdata;
for(vector<int>::iterator vecItr = useThisVectorToBuildList.begin(); vecItr!=useThisVectorToBuildList.end() ; vecItr++)
{
vdata = *vecItr;
//create new node
newNode = new Node;
newNode->data = vdata;
newNode->next = nullptr;
// if first node - head - hasn't been created yet
if(head==nullptr){
head = newNode;
tail = newNode;
}
else{
tail->next = newNode;
tail = newNode;
}
}
return head;
}
ここで(私は、ヘッドノードのデータ値をプリントアウトしようとしている)のようなものを私の主なルックスです:
/* ---------------------------- MAIN --------------------------------------- */
int main()
{
vector<int> populateList{1,2,3,3,1,24,5};
Node *listHead = buildList(populateList);
cout << listHead->data << endl;
return 0;
}
はイテレータの仕組みへと理解の欠如があるようです。 このコードでは、コードを実行すると「バスエラー:10」になります。
しかし 私は少し(私は以下の変更のみを示しています)は、既存のコードを変更した場合:
Node* buildList(vector<int> &useThisVectorToBuildList)
{
...
for(vector<int>::iterator vecItr = useThisVectorToBuildList.begin(); vecItr!=useThisVectorToBuildList.end() ; vecItr++)
{
vdata = *vecItr;
cout << vdata << endl; // ADDED THIS LINE TO DEBUG and print value.
//create new node
newNode = new Node;
newNode->data = *vecItr;
newNode->next = nullptr;
...
}
return head;
}
私は出力を得る:
1
Segmentation fault: 11
そして、場合私はこう変わる:
Node* buildList(vector<int> &useThisVectorToBuildList)
{
Node *newNode, *head, *tail;
for(vector<int>::iterator vecItr = useThisVectorToBuildList.begin(); vecItr!=useThisVectorToBuildList.end() ; vecItr++)
{
cout << *vecItr << endl; // ADDED THIS TO DEBUG. NOTE LACK OF TEMP VARIABLE "int vdata"
//create new node
newNode = new Node;
newNode->data = *vecItr;
newNode->next = nullptr;
...
}
return head;
}
適切な出力が得られます。
1
2
3
3
1
24
5
1
なぜ私は単に変数に値を代入する前に値イテレータのポイントをプリントアウトすることにより、適切な出力を見ていますか?
あなたのコンパイラが初期化されていない変数について警告する必要がありますが、このWARNING_を読み、修正する必要があり_and。 – tkausl
OSXのg ++は警告を出さなかった:/ – Raaj