1
2 #include <string>
3 #include <list>
4 #include <iostream>
5 #include <vector>
6
7 using std::cout;
8 using std::endl;
9 using std::list;
10 using std::iterator;
11 using std::string;
12
13 typedef std::list <int> List;
14 List a;
15 List::iterator it1;
16 int main()
17 {
18
19 a.push_back(1);
20 a.push_back(2);
21 a.push_back(3);
22 a.push_back(4);
23 a.push_back(5);
24
25 for(it1 = a.begin(); it1 != a.end(); )
26 {
27 a.erase(it1); //返回指向下一个
28 cout<<*it1<<endl; //验证it1为下移,
29 --it1;//此处去掉,报错
30 ++it1;
31 }
32 }
33
34 使用STLport5.1.4
35 似乎h文件上面推荐用
36
37 iterator erase(iterator __first, iterator __last) {
38 while (__first != __last)
39 erase(__first++);
40 return __last;
41 }
42
43
该程序正确并输出正常
1
2 for(it1 = a.begin(); it1 != a.end(); )
3 {
4 a.erase(it1++); //返回指向下一个
5 cout<<*it1<<endl; //验证it1为下移,
6
7 }
8
9
这个也可以,
1 for(it1 = a.begin(); it1 != a.end(); )
2 {
3 a.erase(it1);
4 cout<<*it1<<endl;
5 ++it1;
6 }
7
8
报runtime错
这个也可以:
1 for(it1 = a.begin(); it1 != a.end(); )
2 {
3 it1=a.erase(it1);
4 cout<<*it1<<endl;
5
6 }
7
8