🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.std.c++
Article #2554

Re: Modifying STL containers via an iterator

#2554
From: Jason Merrill
Date: Wed, 15 Nov 1995 01:33
43 lines
2024 bytes
>>>>> 40763  <James> writes:

> One of the most useful idioms I've found with lists looks something
> like the following (with my list class):

> 	GB_DLListOf< T >    list ;
> 	for ( GB_DLListOf::Index i( list ) ; ! i.finished() ; ++ i )
> 	{
> 	    if ( someCondition( list[ i ] ) )
> 	        list.remove( i ) ;
> 	}

> To do the same with STL requires something like the following:

> 	list< T >           myList ;
> 	list< T >::iterator i( myList.begin() ) ;
> 	while ( i != myList.end() )
> 	{
> 	    list< T >::iterator      curr( i ++ ) ;
> 	    if ( someCondition( *curr ) )
> 	        myList.erase( curr ) ;
> 	}

> The incrementation *must* take place before the erase in order to work
> correctly.

This should work:

	list< T >           myList ;
	for ( list< T >::iterator i( myList.begin() ); i != myList.end(); )
	{
	    if ( someCondition( *i ) )
	        myList.erase( i++ ) ;
	}

Looks pretty similar, doesn't it?  Note that operator++ increments i
before it returns a value to be used in the erase.

Jason
---
[ 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: <u9ka52iwn4.fsf@yorick.cygnus.com>
Path: arc1-ca.pugleaf.net!in2.uu.net!bounce-back
References: <47l8qe$9fk@bcarh8ab.bnr.ca> <9511122227.AA22118@eniac.glue.ch> <9511141139.AA01526@lts.sel.alcatel.de>

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!in2.uu.net!bounce-back
Date: 15 Nov 95 01:33:26 GMT
Approved: fjh@cs.mu.oz.au
From: jason@cygnus.com (Jason Merrill)
Newsgroups: comp.std.c++
Subject: Re: Modifying STL containers via an iterator
X-Original-Date: 14 Nov 1995 15:50:23 -0800
Organization: Cygnus Support, Mountain View, CA
Message-ID: <u9ka52iwn4.fsf@yorick.cygnus.com>
References: <47l8qe$9fk@bcarh8ab.bnr.ca> <9511122227.AA22118@eniac.glue.ch>
 <9511141139.AA01526@lts.sel.alcatel.de>
In-Reply-To: James Kanze US/ESC 60/3/141 #40763's message of 14 Nov 1995
 20:38:01 GMT
X-Newsreader: Gnus v5.0
X-Auth: PGPMoose V1.1 PGP comp.std.c++
 iQBFAgUBMKlDkOEDnX0m9pzZAQFODQF+J7e7OiV/0ZWVtq7ymW2+Ebdn5auqO6hl
 h+RZUDYEHaqHeadaUiqIt+N/o1xhY+ox
 =7kaV