Article View: comp.std.c++
Article #2587Re: Does remove_if invalidate iterators?
From: J. Kanze
Date: Sat, 18 Nov 1995 03:15
Date: Sat, 18 Nov 1995 03:15
48 lines
2495 bytes
2495 bytes
Bowden Wise (wiseb@cs.rpi.edu) wrote:
|> I am using the remove_if () construct to remove a series of values
|> from a list<int> ... I am doing a loop like this:
|> list<int>::const_iterator next (l.begin());
|> list<int>::iterator last (l.begin());
|> while ( next != l.end() )
|> {
|> // increment before remove_if
|> list<int>::const_iterator cur ( next++ );
|> int val = *cur;
|> if ( val*val > MAX )
|> break;
|> //
|> last = remove_if (last, l.end(), bind2nd (myPred, val));
Attention: if bind2nd(myPred,val)( *next ) is true, the element referred
to by next will be erased, invalidating it.
|> }
|> However, I am finding that each time remove_if is called, it *skips* the
|> next item in the sequence. So, does the remove_if mess up the semantics
|> of my iterator? What should I do?
Off hand, I'd say you need a list class with a more complicated
iterator; one that works even if you delete the element it refers to.
Although I suspect that there is a way to do this with the STL classes,
it doesn't occur to me off hand.
On the other hand, where *should* next point if the corresponding
element has been removed? Although in my own list class, incrementation
works as you seem to expect it to, any attempt to delete the incremented
element will fail (with an assertion failure). So you're really not
much better off.
--
James Kanze (+33) 88 14 49 00 email: kanze@gabi-soft.fr
GABI Software, Sarl., 8 rue des Francs Bourgeois, 67000 Strasbourg, France
Conseils, itudes et rialisations en logiciel orienti objet --
-- A la recherche d'une activiti dans une region francophone
---
[ comp.std.c++ is moderated. Submission address: std-c++@ncar.ucar.edu.
Contact address: std-c++-request@ncar.ucar.edu. The moderation policy
is summarized in http://dogbert.lbl.gov/~matt/std-c++/policy.html. ]
Technical Details
Message-ID:
<48hq2b$1nr@gabi.gabi-soft.fr>Path:
arc1-ca.pugleaf.net!in1.uu.net!bounce-backReferences:
<48g1hu$gf9@engnews1.eng.sun.com>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!in1.uu.net!bounce-back Date: 18 Nov 95 03:15:22 GMT Approved: fjh@cs.mu.oz.au From: kanze@gabi-soft.fr (J. Kanze) Newsgroups: comp.std.c++ Subject: Re: Does remove_if invalidate iterators? X-Original-Date: 17 Nov 1995 12:01:31 +0100 Organization: GABI Software, Sarl. Message-ID: <48hq2b$1nr@gabi.gabi-soft.fr> References: <48g1hu$gf9@engnews1.eng.sun.com> X-Newsreader: TIN [version 1.2 PL2] X-Auth: PGPMoose V1.1 PGP comp.std.c++ iQBFAgUBMK1P5OEDnX0m9pzZAQGGkgF+JsIc34agEajP0qAnXQ3P1VQv/x3FsmXm N+wbJ8WG9tofGQXiIYTqi4A4smfn1tia =HrY5