Re: Erasing objects satisfying a criterion from std::map

From: Thomas Matthews (Thomas_MatthewsSpamBotsSuck_at_sbcglobal.net)
Date: 01/10/05


Date: Mon, 10 Jan 2005 11:43:58 GMT

KaizerSose@gmail.com wrote:
> So what is the correct way of doing it?
>

There is no "correct" method. Some are more efficient,
some use less statements.

The fundamental approach is to iterate through the
map and find elements that match the criterion. Erase
the item, then start from the beginning to find the
next item. Remember that iterators are not valid after
an erase.

Another alternative is re-sort the map according to
the criterion and then erase the first item as long as
it matches. Then restore the sort order of the map.
A technique of building a view (a container of pointers
or iterators) will not be efficient since the view
must be recreated after an erase on the map (since
an erase invalidates the pointers).

The main issue is that iterators become invalid
after an erase. The elements in the container may
change positions.

-- 
Thomas Matthews
C++ newsgroup welcome message:
          http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq:   http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
          http://www.comeaucomputing.com/learn/faq/
Other sites:
     http://www.josuttis.com  -- C++ STL Library book
     http://www.sgi.com/tech/stl -- Standard Template Library


Relevant Pages

  • Re: Erasing objects satisfying a criterion from std::map
    ... > map and find elements that match the criterion. ... Remember that iterators are not valid after ... > an erase. ... > an erase invalidates the pointers). ...
    (comp.lang.cpp)
  • Re: Efficiency of map and vector iterators
    ... >> What happens if you cache the return value of endwhen using the map ... > iterators to the elementsbeing erased, ... Constructed an empty map and an empty ...
    (comp.lang.cpp)
  • Re: Help with some logic, best way to update a container.
    ... you could use make_pair to avoid having to specify the template ... you might implement in a map, as 65=1 (treating the letters as integers because you gave ... Incrementing iter is undefined after you erase it. ... For containers whose erase returns an iterator, ...
    (microsoft.public.vc.mfc)
  • Re: Help with some logic, best way to update a container.
    ... you could use make_pair to avoid having to specify the template ... Now that I look at my code, I see that indeed I use the <iterator, bool> return from ... you might implement in a map, as 65=1 (treating the letters as integers because you gave ... the documentation is sloppy; the erase method does not state this behavior. ...
    (microsoft.public.vc.mfc)
  • Re: vector.erase() ?
    ... if they are reverse iterators. ... because the erase would invalidate the new ...
    (comp.lang.cpp)