Re: erase/delete for all containers

Discussion in 'C++' started by Victor Bazarov, Aug 22, 2003.

  1. "sks_cpp" <> 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
     
    Victor Bazarov, Aug 22, 2003
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. tom_usenet
    Replies:
    1
    Views:
    332
    John Harrison
    Aug 23, 2003
  2. erase vs. erase

    , Mar 25, 2006, in forum: C++
    Replies:
    7
    Views:
    388
    Pete Becker
    Mar 30, 2006
  3. Replies:
    3
    Views:
    340
    Default User
    Jul 9, 2007
  4. Replies:
    7
    Views:
    575
    Pete Becker
    Jan 25, 2008
  5. Sebastian Mach
    Replies:
    5
    Views:
    340
Loading...

Share This Page