In article <11**********************@m79g2000cwm.googlegroups .com>,
mo********@yahoo.com says...
Hi,
I know if you call erase when you iterate through map you will crash.
Ex:
map<int,doublem;
// insert something
for ( map<int, double>::iterator i = m.begin(); i != m.end(); i++ )
if ( i->second < 0 ) m.erase(i);
This will crash because erase() will corrupt iterator. Now what I do I
insert key into list and erase each key. After first loop. Is there way
to do this erase in the same search loop?
I'm not sure I have straight what you're trying to accomplish.
From your code it looks like you want to copy only a subset of the items
from the map into a list and erase only those items from the map (I.e.
basically move each qualifying item from the map to the list).
If that's the case, then most of what you have is reasonable. The main
change you need is to use the return value from m.erase(). erase()
returns an iterator to the next item after the one you just erased, so
your loop could look something like:
i = m.begin();
while (i!=m.end())
if (i->second < 0) {
// your_list.push_back(*i);
i = m.erase(i);
}
else
++i;
OTOH, your description sounds like you're trying to copy all the
elements from a map into a list, and then basically destroy the map. If
that's the case, you're probably better off with something like:
std::copy(your_map.begin(), your_map.end(),
std::back_inserter(your_list));
your_map.clear();
If you remove the items from the map individually, it'll re-balance the
tree as your removals change the balance. Since you're removing all the
items, the time spent re-balancing the tree is wasted. clear() knows
it's going to produce an empty tree, so it can avoid re-balancing as it
removes nodes.
--
Later,
Jerry.
The universe is a figment of its own imagination.