stl list 正确删除节点程序实例

#include<stdio.h>
#include<list>
#include<string.h>
using namespace std;
#define ARR_SIZE 20
char * genArr(const char *str)
{
char * arr = new char [ARR_SIZE];
memset(arr, 0, ARR_SIZE);
int len = strlen(str)<ARR_SIZE?strlen(str):ARR_SIZE;
strncpy(arr, str, len);
return arr;
}
list<char *>* genList()
{
list<char *> *mylist = new list<char*>;
mylist->push_back(genArr("I am first"));
mylist->push_back(genArr("I am second"));
mylist->push_back(genArr("I am third"));
mylist->push_back(genArr("I am fourth"));
return mylist;
}
void showList(list<char*> *mylist)
{
if(NULL==mylist || mylist->empty())
{
printf("nothing to show ");
return;
}
printf("list size is %d ", mylist->size());
for(list<char *>::iterator it = mylist->begin();it!=mylist->end();it++)
{
printf("%s ", *it);
}
}
void removeElem(list<char *> * mylist, const char * str)
{
for(list<char*>:: iterator it = mylist->begin();it!=mylist->end();)
{
char *tmp = *it;
printf("before erase %s ", *it);
if(!strncmp(tmp, str, strlen(str)))
{
//it = mylist->erase(it);
mylist->erase(it++);
printf("after erase %s ", *it);
delete tmp;
tmp = NULL; 
}
else
it++;
}
}

void removeList(list<char *> *mylist)
{
if(NULL==mylist || mylist->empty())
{
printf("nothing to remove ");
// return;
}
printf("before remove list size is %d, address is %p ", mylist->size(),mylist);
for(list<char *>::iterator it = mylist->begin();it!=mylist->end();)
{
it = mylist->erase(it);
printf("remove list !!!!!!! ");
}
printf("after remove list size is %d, address is %p ", mylist->size(),mylist);
}
int main()
{
list<char *> *mylist = genList();
showList(mylist);
removeElem(mylist,"I am second");
showList(mylist);
removeList(mylist);
showList(mylist);
return 1;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

原文地址:https://www.cnblogs.com/agiletiger/p/4888242.html