STL在迭代的过程,删除指定的元素

时间:2022-08-22 17:06:34

直接在Code。在 Picture

#include <iostream>
#include <list> using namespace std; // STL在迭代的过程中,删除指定的元素
int main()
{
list<int> listTest; listTest.push_back(-1);
listTest.push_back(-1);
listTest.push_back(-1);
listTest.push_back(-1); cout<<"list size: "<<listTest.size()<<endl; list<int>::iterator itList; for (itList=listTest.begin(); itList != listTest.end(); /*no itList++ !!*/ )
{
cout<<"data: "<<*itList<<endl; // 第一种方法
if (*itList <= 0)
itList = listTest.erase(itList);
else
++itList;
}
cout<<"list size: "<<listTest.size()<<endl;
cout<<"======================================"<<endl; listTest.push_back(-1);
listTest.push_back(-1);
listTest.push_back(-1);
listTest.push_back(1); cout<<"list size: "<<listTest.size()<<endl; for (itList=listTest.begin(); itList != listTest.end(); ++itList)
{
cout<<"data: "<<*itList<<endl; // 另外一种方法
if (*itList <= 0)
*itList = 0; // 做个记录标志。等待迭代完进行回收
} listTest.remove(0); // 回收 0 cout<<"list size: "<<listTest.size()<<endl;
cout<<"======================================"<<endl; return 0; }

执行结果:

STL在迭代的过程,删除指定的元素

版权声明:本文博主原创文章。博客,未经同意,不得转载。 http://blog.csdn.net/core__code