Reputation: 3662
vector<int> nums;
nums.push_back(0);
nums.push_back(1);
nums.push_back(2);
nums.push_back(3);
vector<int>::iterator it = nums.begin();
it++;
cout << "it points to " << *(it) << endl;
for(vector<int>::iterator jt = nums.begin(); jt != nums.end(); jt++) {
cout << (*jt) << endl;
}
cout << endl;
nums.insert(it, 100500);
cout << ">> insert(it, 100500)" << endl << endl;
cout << "it points to " << *(it) << endl;
for(vector<int>::iterator jt = nums.begin(); jt != nums.end(); jt++) {
cout << (*jt) << endl;
}
cout << endl;
it++;
cout << ">> it++" << endl << endl;
cout << "it points to " << *(it) << endl;
for(vector<int>::iterator jt = nums.begin(); jt != nums.end(); jt++) {
cout << (*jt) << endl;
}
cout << endl;
nums.insert(it, 100800);
cout << ">> insert(it, 100800)" << endl << endl;
cout << "it points to " << *(it) << endl;
for(vector<int>::iterator jt = nums.begin(); jt != nums.end(); jt++) {
cout << (*jt) << endl;
}
cout << endl;
it++;
cout << ">> it++" << endl << endl;
cout << "it points to " << *(it) << endl;
for(vector<int>::iterator jt = nums.begin(); jt != nums.end(); jt++) {
cout << (*jt) << endl;
}
cout << endl;
returns
it points to 1
0
1
2
3
>> insert(it, 100500)
it points to 1
0
100500
1
2
3
>> it++
it points to 2
0
100500
1
2
3
>> insert(it, 100800)
it points to 100800
134352185
0
100500
1
2
3
>> it++
it points to 2
134352185
0
100500
1
2
3
I cant understand anything. help!
mingw g++ 4.5.0 win32
Upvotes: 0
Views: 612
Reputation: 385295
This is not a bug. You failed to properly read the std::vector
documentation before leaping to the conclusion that the software was in error; in fact, vector insertions invalidate all iterators.
Upvotes: 0
Reputation: 355207
When you insert a new element into a vector
, any iterators to elements after the insertion position are invalidated and if a reallocation occurs then all iterators into the container are invalidated. A reallocation occurs any time that v.capacity() - v.size()
is less than the number of elements you are trying to insert.
When an iterator is invalidated, it means that the iterator can no longer be used. It is invalid.
This overload of insert
returns a new iterator to the inserted element, so you can replace this:
nums.insert(it, 100500);
with this:
it = nums.insert(it, 100500);
The rules for when iterators are invalidated are different for each container and you must be careful to understand them. One of the best references for the STL is the SGI STL documentation. The iterator invalidation rules are usually listed in a footnote on each of the container documentation pages.
Note that the SGI STL documentation is not the official documentation for the C++ Standard Library and there are some subtle differences, but usually those differences are not particularly important; one thing to note is that some pieces of the SGI STL are not included in the C++ Standard Library and some parts of the C++ Standard Library are not part of the SGI STL.
Upvotes: 6