首先以示例代码为例:
vector<int> v;
//添加一些元素
fir(int i=0; i<10; ++i)
v.push_back(i);
int* my_favorite_element_ptr = &v[3];
cout<<"My favorite element = "<<(*my_favorite_element_ptr)<<endl;
cout<<"Its address = "<<my_favorite_element_ptr<<endl;
cout<<"Adding more elements.."<<endl;
//添加更多元素
for(int i=0; i<100; ++i)
v.push_back(i*10);
cout<<"My favorite element = "<<(*my_favorite_element_ptr)<<endl;
cout<<"Its address = "<<&v[3]<<endl;
对于以上的代码,会发生什么样的情况?我们创建了一个包含10个元素的vector,并出于某种原因决定保存一个指向索引位置为3的元素的指针。接着,我们向这个vector添加了另一些元素,并试图复用前面所保存的指针。这段代码会有什么错误吗?