AA.remove in foreach && AA = new vs cleaning
Steven Schveighoffer
schveiguy at yahoo.com
Wed Oct 21 20:08:46 PDT 2009
On Wed, 21 Oct 2009 23:06:47 -0400, Saaa <empty at needmail.com> wrote:
> Is there anything with removing the current key in a foreach?
>
> foreach (K k, ; aa)
> {
> ..
> aa.remove(k);
> }
>
Yes, behavior is undefined.
from http://digitalmars.com/d/2.0/statement.html#ForeachStatement :
"The aggregate must be loop invariant, meaning that elements to the
aggregate cannot be added or removed from it in the [loop body]"
I have gotten around this in dcollections by removing elements outside the
loop body. See for example the keypurge function of HashMap
(http://www.dsource.org/projects/dcollections/docs/current/dcollections.HashMap.html)
-Steve
More information about the Digitalmars-d-learn
mailing list