Ich schrieb gerade ein Testprogramm auf Iteratoren in Vektor, Am Anfang hatte ich gerade einen Vektor erstellt und initialisierte es mit einer Reihe von Zahlen 1-10.Schleife mit Iterator in einem Vektor
Danach hatte ich einen Iterator "MyIterator" und einen Const-Iterator "Iter" erstellt. Ich hatte iter benutzt, um den Inhalt des Vektors anzuzeigen.
Später hatte ich "myIterator" zu "anotherVector.begin()" zugewiesen. Sie zeigen also auf dasselbe.
von
//cout << /* *myIterator << */"\t" << *(anotherVector.begin()) << endl;
geprüft
so in der zweiten Schleife Iterator i gerade ersetzt "anotherVector.begin()" mit myIterator.
Aber das produzierte eine andere Ausgabe.
Code ist:
vector<int> anotherVector;
for(int i = 0; i < 10; i++) {
intVector.push_back(i + 1);
cout << anotherVector[i] << endl;
}
cout << "anotherVector" << endl;
//*************************************
//Iterators
cout << "Iterators" << endl;
vector<int>::iterator myIterator;
vector<int>::const_iterator iter;
for(iter = anotherVector.begin(); iter != anotherVector.end(); ++iter) {
cout << *iter << endl;
}
cout << "Another insertion" << endl;
myIterator = anotherVector.begin();
//cout << /* *myIterator << */"\t" << *(anotherVector.begin()) << endl;
myIterator[5] = 255;
anotherVector.insert(anotherVector.begin(),200);
//for(iter = myIterator; iter != anotherVector.end(); ++iter) {
//cout << *iter << endl;
//}
for(iter = anotherVector.begin(); iter != anotherVector.end(); ++iter) {
cout << *iter << endl;
}
Ausgabe mit
for(iter = anotherVector.begin(); iter != anotherVector.end(); ++iter) {
cout << *iter << endl;
}
gibt:
Iterators
1
2
3
4
5
6
7
8
9
10
Another insertion
200
1
2
3
4
5
255
7
8
9
10
und Ausgang mit
for(iter = myIterator; iter != anotherVector.end(); ++iter) {
cout << *iter << endl;
}
gibt:
Iterators
1
2
3
4
5
6
7
8
9
10
Another insertion
0
0
3
4
5
255
7
8
9
10
81
0
1
2
3
4
5
6
7
8
9
10
0
0
0
0
0
0
0
0
97
0
200
1
2
3
4
5
255
7
8
9
10
Warum gibt es so viel Unterschied, wenn sie nur die gleiche Adresse zeigen.
Anstatt meine eigene Antwort zu veröffentlichen, da Sie mich dazu schlagen, [hier ist der Link auf 'Vektor' Iterator Invalidation] (http://en.cppreference.com/w/cpp/container/vector#Iterator_invalidation) als Referenz . – ShadowRanger
danke dafür, ich hatte es mit dem Adress-Operator bestätigt. –