从STL中的list删除元素
2009-10-31 11:24
316 查看
正确版本:
1 #include <iostream>
2 #include <list>
3 #include <algorithm>
4 using namespace std;
5
6 int main(int argc, char* argv[])
7 {
8 list<int> MyList;
9
10 for (int i = 0; i < 10; i++)
11 {
12 MyList.push_back(i);
13 }
14
15 list<int>::iterator Itor;
16
17 for ( Itor = MyList.begin(); Itor != MyList.end(); )
18 {
19 if ( *Itor == 4 )
20 {
21 Itor = MyList.erase(Itor);
22 }
23 else
24 {
25 Itor++;
26 }
27 }
28
29 copy(MyList.begin(), MyList.end(), ostream_iterator<int>(cout, " ") );
30 cout<<endl;
31
32 return 0;
33 }
错误版本:
1 #include <iostream>
2 #include <list>
3 #include <algorithm>
4 using namespace std;
5
6 int main(int argc, char* argv[])
7 {
8 list<int> MyList;
9
10 for (int i = 0; i < 10; i++)
11 {
12 MyList.push_back(i);
13 }
14
15 list<int>::iterator Itor;
16
17 for ( Itor = MyList.begin(); Itor != MyList.end(); Itor++)
18 {
19 if ( *Itor == 4 )
20 {
21 MyList.erase(Itor); //断链,出错地方
22 }
23 }
24
25 copy(MyList.begin(), MyList.end(), ostream_iterator<int>(cout, " ") );
26 cout<<endl;
27
28 return 0;
29 }
1 #include <iostream>
2 #include <list>
3 #include <algorithm>
4 using namespace std;
5
6 int main(int argc, char* argv[])
7 {
8 list<int> MyList;
9
10 for (int i = 0; i < 10; i++)
11 {
12 MyList.push_back(i);
13 }
14
15 list<int>::iterator Itor;
16
17 for ( Itor = MyList.begin(); Itor != MyList.end(); )
18 {
19 if ( *Itor == 4 )
20 {
21 Itor = MyList.erase(Itor);
22 }
23 else
24 {
25 Itor++;
26 }
27 }
28
29 copy(MyList.begin(), MyList.end(), ostream_iterator<int>(cout, " ") );
30 cout<<endl;
31
32 return 0;
33 }
错误版本:
1 #include <iostream>
2 #include <list>
3 #include <algorithm>
4 using namespace std;
5
6 int main(int argc, char* argv[])
7 {
8 list<int> MyList;
9
10 for (int i = 0; i < 10; i++)
11 {
12 MyList.push_back(i);
13 }
14
15 list<int>::iterator Itor;
16
17 for ( Itor = MyList.begin(); Itor != MyList.end(); Itor++)
18 {
19 if ( *Itor == 4 )
20 {
21 MyList.erase(Itor); //断链,出错地方
22 }
23 }
24
25 copy(MyList.begin(), MyList.end(), ostream_iterator<int>(cout, " ") );
26 cout<<endl;
27
28 return 0;
29 }
相关文章推荐
- 对C++ STL,list元素的循环删除操作 //断链,出错地方
- 从STL中的list删除元素
- STL中list,遍历删除元素注意事项
- STL删除list元素
- C++/STL用erase删除元素(vector,deque),(list,set,map)
- stl的vector,map,list删除元素
- STL双向链表之删除重复元素(list)
- STL 中list删除元素
- 关于STL的list,vector等用迭代器iterator,用erase删除元素出现的问题。
- 从STL中的list删除元素
- STL链表之删除指定元素(list)
- 关于STL的list,vector等用迭代器iterator,用erase删除元素出现的问题。
- 对C++ STL,list元素的循环删除操作
- 对C++ STL,list元素的循环删除操作
- C++/STL_利用remove_if 删除vector,list,deque满足条件的元素
- 一个List,怎么删除其中不想要的元素
- python中List添加、删除元素的几种方法
- Java_List元素的遍历和删除
- list列表删除元素
- STL容器迭代过程中删除元素技巧(转)