vecor预分配内存溢出2
vector预分配内存溢出导致原始的 迭代器 失效
consider what happens when you add the one additional object that causes the vector to reallocate storage and move it elsewhere. The iterator’s pointer is now pointing off into nowhere:
This illustrates the concept of iterator invalidation. Certain operations cause internal changes to a container’s underlying data, so any iterators in effect before such changes may no longer be valid afterward.
#include<iostream> #include<iterator> #include<vector> using namespace std; int main() { vector<int> vi(10, 0); ostream_iterator<int> out(cout, " "); vector<int>::iterator i = vi.begin(); *i = 47; copy(vi.begin(), vi.end(), out); cout << endl; //force it to move memory(could also just add enough objects) vi.resize(vi.capacity() + 1); //now i points to wrong memory *i = 48; copy(vi.begin(), vi.end(), out);//no change to vi[0] }