Can remove AA elements during foreach?

Steven Schveighoffer schveiguy at yahoo.com
Sat Feb 16 17:10:43 PST 2013


On Sat, 16 Feb 2013 18:59:59 -0500, Nick Sabalausky  
<SeeWebsiteToContactMe at semitwist.com> wrote:

> Is this both legal and safe?:
>
>     foreach(key; assocArray)
>     if(key != "foobar")
>         assocArray.remove("foobar");
>
> If not, then what about this?:
>
>     foreach(key; assocArray.byKey())
>     if(key != "foobar")
>         assocArray.remove("foobar");
>

Both are unsafe.

Note that with Dcollections, there is a special purge feature that allows  
safe removal while traversing:

foreach(ref doPurge, key, value; &hashMap.purge)
     doPurge = (key != "foobar");

All dcollections' classes support this.

There is a keys collection, but that does not support purge.  I can  
actually add it pretty easily though...

-Steve


More information about the Digitalmars-d-learn mailing list