"Pieter Thysebaert" <> wrote in message news:c8010s$a5l$...
>
>
> Hello,
>
> I've got a question conerning erasing key-value pairs from a std::map while
> iterating over it.
>
> According to the STL docs, erasing an element in a map invalidates all
> iterators pointing to that element
>
> so
>
> for (map<...>::iterator i = mymap.begin(); i != mymap.end(); i++) {
> if (test(i)) {
> mymap.erase(i);
> mymap.insert(newelement);
> }
> }
>
> looks like bad practice, and it does crash when it gets executed, at least
> on one machine i've run such code on.
>
> So my question is, how do I conveniently erase the "current" element in a
> map on the fly while I'm iterating over it? (I admit that this sounds as
> weird in English as it sounds in C++)?
>
> Thanx,
>
> Pieter
I've run into that situation many times with maps, lists and other containers,
and the easiest solution, I've found, is to get a copy of i called j, decrement i,
then erase (*j). Like so:
map<K, V> mymap; // where K and V are types
map<K, V>::iterator i, j; // get some iterators
for (i = mymap.begin(); i != mymap.end(); i++)
{
if (test(i))
{
j = i; // get temp. copy of i
--i; // gonna kill place where i pointed, so back up!
mymap.erase(j); // erase element where i used to point
mymap.insert(newelement); // automatically sorted; where did it go?
}
}
If i was decremented and (*j) erased, then when execution resumes at the
top of the loop, i will be incremented to the next un-erased item.
Also be aware that there's no guarantee the inserted item went the same
place as the deleted one; map is automatically sorted by key, so the new
element could end up anywhere, depending on sort order.
--
Cheers,
Robbie Hatley
Tustin, CA, USA
email: lonewolfintj at pacbell dot net
web: home dot pacbell dot net slant earnur slant
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---