3
其实这是一个非常普遍的问题,同时对于其他的容器vector,deque,map,list,stack,queue,priority_queue,multimap,set,multiset,hash_map所有的都适用的!
详情请看:


看看问题的提出:
引用

I have a list of pointers. e.g

A* a = new A(); // A is a class
stl::list list_a;


I am inserting object of class in the after allocating memeory thru new
operator.


But when i want to erase all elements from the list. my progam crashes.
I delete element by using a iterator.


A * temp = NULL;
stl::list::iterator Iter,
stl::list::iterator IterTemp;
for( Iter = list_a.begin() ; Iter != list_a.end()  ;  ){
          Iter = list_a.begin();
          temp = *Iter;
          IterTemp  = Iter;
          Iter++;
          list_a.erase(IterTemp);
          delete temp;



}


At erase line my program crashes and debugger shows some exception in
erase function.

Any help is greatly appreciated.


Thanks in advance.
Vibhor Mahajan


对他的问题,熟悉的人明显就可以看到问题非常明显,这位朋友的代码可以说写的非常糟糕!

当然,要删除这个指针还是不难的!
看看一些正确的回复吧!

引用

Really, when you want to do that kind of things, the *best* way to go
IMHO is :

std::list::iterator it;
for(it = list_a.begin() ; it != list_a.end() ; ++it)
{
 delete *it;


}


list_a.clear();

It will be much faster and much more readable.


引用

First of all, it should be std::list, not stl::list.

Second, rewrite your delete loop as follows:


for (iter = list_a.begin(); iter != list_a.end ; )
{
    delete (*iter);
    iter = list_a.erase(iter);
}


下面的回复更加精彩!
引用

or even:

// template is more generic
template
struct DeletePointer : public std::unary_function
{
    void operator()(T* ptr) { delete ptr; }



};


std::for_each(list_a.begin(), list_a.end(), DeletePointer());
list_a.clear();



希望这篇文章能够给大家带来一些帮助
Tags: , , | 引用(0)
45 Homepage
2008/08/25 13:52
question
huzhangyou2002 Email Homepage
2006/07/16 12:39
我还是很喜欢他的简洁
呵呵
虽然效率并不是最好
skywind Email
2006/07/16 10:17
最后一个方案,用函数对象的,其实比较累
分页: 1/1 第一页 1 最后页
发表评论
表情
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
打开HTML
打开UBB
打开表情
隐藏
记住我
昵称   密码   游客无需密码
网址   电邮   [注册]