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

realhet real_het at hotmail.com
Sun Aug 29 09:15:45 UTC 2021


On Sunday, 29 August 2021 at 09:02:52 UTC, 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.

I did a small test using .byKey, it's totally safe, just as you 
said. Thank You!

```
void main(){
     int[int] aa = [1:10, 2:20, 3:30];

     auto k1 = aa.keys;   auto k2 = aa.byKey;

     aa.remove(2);

     writeln(typeof(k1).stringof);  foreach(k; k1) writeln(k);
     writeln(typeof(k2).stringof);  foreach(k; k2) writeln(k);
}
```


More information about the Digitalmars-d-learn mailing list