AA.remove in foreach && AA = new vs cleaning

Steven Schveighoffer schveiguy at yahoo.com
Wed Oct 21 21:46:53 PDT 2009


On Thu, 22 Oct 2009 00:45:36 -0400, Saaa <empty at needmail.com> wrote:

> Steven Schveighoffer wrote:
>> 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 suspect removing the current key isn't a problem in the current
> implementation;
> Been using it quite a lot without any problems :)

It may well sometimes work, but it's not defined to work.  I've seen  
instances where it caused problems (i.e. segfaults).  You may just not  
have hit that threshold.

> But I've changed everything to new the array afterwards as I deleted all  
> the
> keys anyways.

Not sure what you mean here.

>>
>> 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)
> Do you add the ones to be deleted to a dynamic array or do you loop
> over all elements afterwards? I expect the first :)

I delete them as they are requested to be deleted.  Since the deletion is  
done by the opApply function, it has knowledge of when it is ok to delete  
the element, and can save off any necessary structural information needed  
to get to the next element.

It makes for an efficient method to traverse and remove in one pass.

-Steve


More information about the Digitalmars-d-learn mailing list