Is removing elements of AA in foreach loop safe?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Thu Aug 29 12:25:56 UTC 2019


On Thursday, August 29, 2019 4:11:58 AM MDT berni via Digitalmars-d-learn 
wrote:
> Iterating of some structure and removing elements thereby is
> always errorprone and should be avoided. But: In case of AA, I've
>
> got the feeling, that it might be safe:
> > foreach (k,v;ways)
> >
> >     if (v.empty)
> >
> >         ways.remove(k);
>
> Do you agree? Or is there a better way to achieve this?

No, it's not safe to do that. If you insert or remove any elements from an
AA while looping over it, you're going to have weird behavior. If you want
to remove elements in a loop, then you'll need to do something like put each
key that you want to remove in a dynamic array while looping over the AA and
then loop over the dynamic array to remove the elements from the AA.

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list