Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > Re: erase/delete for all containers

Reply
Thread Tools

Re: erase/delete for all containers

 
 
Victor Bazarov
Guest
Posts: n/a
 
      08-22-2003
"sks_cpp" <(E-Mail Removed)> wrote...
> // C is a container of pointers
>
> template<typename Container>
>
> void deleteObjects(Container& C)
>
> {
>
> C::iterator i = C.begin();
>
> while( i != C.end() )
>
> {
>
> C::iterator j = i++;
>
> delete *j;
>
> C.erase(j);
>
> }
>
> }
>
> I read online somewhere that this works for list, set, and map but NOT
> vector and deque. Is that correct?


Yes, I'm afraid so. When you erase an element of a vector or a deque
using an iterator, all iterators pointing to objects _after_ the one
that is deleted become invalid. If 'C' is a vector, 'i' becomes
invalid after you erase 'j'. Any operation with it causes undefined
behaviour. That's why 'erase' returns an iterator for sequences.
You should use it:

delete *i;
i = C.erase(i);

There is a hole in the Standard library (and some implementations do
try to correct it) that for associative containers 'erase' does not
return an iterator, it returns 'void'. In any case, your code would
be more efficient if you use

C::iterator i = C.begin();
while (i != C.end())
delete *i++;

C.clear(); // instead of erasing elements every cycle

Victor


 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Are sequence containers not a subset of general containers? Sebastian Mach C++ 5 10-06-2012 07:54 PM
![Oof Topix] All McCain, All Flip-Flop, All the Time Bucky Breeder Computer Support 7 09-27-2008 03:33 PM
SOAP call not returning containers all the time Patrick Put Ruby 0 08-25-2008 05:12 PM
Containers of iterators vs. containers of references clark.coleman@att.net C++ 7 01-25-2008 01:37 PM
Re: erase/delete for all containers tom_usenet C++ 1 08-23-2003 04:06 AM



Advertisments