vecor预分配内存溢出2

时间:2023-03-08 21:11:21

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(, );
ostream_iterator<int> out(cout, " ");
vector<int>::iterator i = vi.begin();
*i = ;
copy(vi.begin(), vi.end(), out);
cout << endl;
//force it to move memory(could also just add enough objects)
vi.resize(vi.capacity() + );
//now i points to wrong memory
*i = ;
copy(vi.begin(), vi.end(), out);//no change to vi[0]
}

vecor预分配内存溢出2