问题的关键是:在删除元素之前,将当前迭代器保存下来。当然,这里仅支持list,因为list的链式的删除一个元素,前面的指针指向下一个元素,vector和queue就不好办了,它们或者是线性的或者是半线性半链式,迭代器会失效
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
#include<iostream>
#include<list>
using namespace std;
int main()
{
list< int *> l;
for ( int i=1;i<=100;i++)
{
int * temp= new int ;
*temp=i;
l.push_back(temp);
}
list< int *>::iterator it=l.begin();
list< int *>::iterator ittemp=l.begin();
for (;it!=l.end();++it)
{
cout<<*(*it)<<endl;
}
it=l.begin();
ittemp=l.begin();
for (;it!=l.end();)
{
ittemp=it;
++it;
delete (*ittemp);
l.erase(ittemp);
}
cout<<l.size()<<endl;
return 0;
}
|
以上就是小编为大家带来的基于list循环删除元素,迭代器失效的问题详解全部内容了,希望大家多多支持服务器之家~