【发布时间】:2016-03-18 20:06:04
【问题描述】:
下面是用于说明我的问题的相同 c++ 代码
我知道其他工作方法,但想知道下面的代码是否错误?
Void pupulatelist()
{
//populating the list with some int pointers,in actual i have some other objects to delete when accessed each time.
for(int i =0;i<5;i++)
{
int *p = new int(i);
list.push_back(p);
}
//want to delete and erase the contents of the above list
// if i dont use erase my actual code is crashing.
for(std::list<int *>::iterator iter = list.begin(); iter != list.end(); ++iter)
{
delete(*iter);
list.erase(iter--);
}
}
【问题讨论】:
-
去掉
list.erase并在循环之后调用list.clear。 (另外,不要使用类型名作为变量名。)