Is it legal to remove a key from associative array while iterating over aa.keys if a foreach loop?

Steven Schveighoffer schveiguy at gmail.com
Sun Aug 29 11:09:28 UTC 2021


On 8/29/21 5:02 AM, Mike Parker wrote:
> On Sunday, 29 August 2021 at 08:55:44 UTC, realhet wrote:
> 
>>
>>
>> Is it safe, or do I have to take a snapsot of the keys range like 
>> this? ->
> 
> You shouldn't remove anything when iterating over `.keys` or `.values`. 
> Use `.byKey` and `.byValue` instead to get ranges that are independent 
> of the aa.

This is exactly the opposite!

The `.keys` property makes a *copy* of all the keys and puts them into 
an array. Same thing with `.values`. It is perfectly safe to remove 
anything  from the associative array while iterating one of those arrays.

The opposite is true for `.byKey` and `.byValue`. Those yield a range 
iterating over the actual data in the associative array. Removing an 
element while iterating one of those could potentially iterate over null 
or stale data, do not do this. While this might work out in some tests, 
eventually you will get bit by this, especially if you remove an element 
you are currently iterating.

-Steve


More information about the Digitalmars-d-learn mailing list