学习c++:vector 中的迭代器失效
void printV(vector<int> &v)
{
for (int i=0; i<v.size(); i++)
{
cout << v[i] << " ";
}
cout << endl;
}
void main341()
{
vector<int> v;
v.resize(4);
v.push_back(1);
printV(v);
cout <<"size: "<< v.size() <<" capacity: "<< v.capacity() << endl;
vector<int>::iterator iter1 = v.end();//报错
//vector<int>::iterator iter1 = v.begin();//ok
//vector<int>::iterator iter1 = v.begin()+4;//ok最后一个元素
//vector<int>::iterator iter1 = v.end()-1;//ok
//vector<int>::iterator iter1 = v.begin()+5;//报错 =end()
v.push_back(2);
cout << "size: " << v.size() << " capacity: " << v.capacity() << endl;
int n = *(iter1);
cout << n << endl;
system("pause");
}
1 不改变capacity的push_back()使得end()失效,不影响end()前的iterator
void main343()
{
vector<int> v;
v.resize(4);
v.push_back(1);
cout <<"size: "<< v.size() <<" capacity: "<< v.capacity() << endl;
vector<int>::iterator iter1 = v.end()-1;
v.push_back(2);
cout << "size: " << v.size() << " capacity: " << v.capacity() << endl;
int n = *(iter1);
cout << n << endl;
system("pause");
}
void main343()
{
vector<int> v;
v.resize(3);
v.push_back(1);
cout <<"size: "<< v.size() <<" capacity: "<< v.capacity() << endl;
vector<int>::iterator iter1 = v.end()-1;
v.push_back(2);
cout << "size: " << v.size() << " capacity: " << v.capacity() << endl;
int n = *(iter1);
cout << n << endl;
system("pause");
}
**2 改变capacity的push_back,原来任何迭代器失效
vector重新分配内存的方式是向下取整 3/2+3=4 **
void main342()
{
vector<int> v;
v.resize(4);
v.push_back(1);
vector<int>::iterator iter1 = v.begin()+1;//no
vector<int>::iterator iter1 = v.begin();//ok
vector<int>::iterator iter1 = v.end();//no
cout << "size: " << v.size() << " capacity: " << v.capacity() << endl;
v.erase(v.begin()+1);
printV(v);
cout << "size: " << v.size() << " capacity: " << v.capacity() << endl;
int n = *iter1;
v.push_back(1);
cout << "size: " << v.size() << " capacity: " << v.capacity() << endl;
cout << n << endl;
system("pause");
}
3 当进行删除操作(erase,pop_back)后,指向删除点的迭代器全部失效;指向删除点后面的元素的迭代器也将全部失效。删除操作不会改变capacity
vector迭代器失效的几种情况
实战c++中的vector系列–copy set to vector(别混淆了reserve和resize)
实战c++中的vector系列–可怕的迭代器失效(vector重新申请内存)
迭代器失效的几种情况总结