Re: removing from set - does it have to be so ugly?
n00m wrote:
I think in-place-erasing totally corrupt the iterator.
Right, whenever you use an iterator to erase an element, the iterator is
invalidated. Further, all iterators referring to the same element are
invalidated. With some containers, even all iterators could be invalidated.
However, all the iterator invalidation rules are documented. While not
mandatory for the C++ standard library, the STL's documentation (available
online) still correctly describes those rules, IIRC.
// r = {0, 3, 5, 7, 9, 10, 11, 15, 20, 25}
set<int>::iterator rit = r.begin();
while (rit != r.end()) {
if (*rit % 2 == 1)
r.erase(rit);
///else
++rit;
}
Yes, this code is wrong. After erasing an element, you are still using the
iterator. Note that even incrementing it means using it. The correct code
requires careful use of a postfix increment operator:
set<int>::iterator rit = r.begin();
while (rit != r.end()) {
if (*rit % 2 == 1)
r.erase(rit++);
else
++rit;
}
Uli
--
Sator Laser GmbH
Gesch??ftsf??hrer: Thorsten F??cking, Amtsgericht Hamburg HR B62 932
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]