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 08:55:44 UTC 2021


Hi,

   //remap the result blobs
   foreach(k; res.blobs.keys){
     int p = map(k);
     if(p!=k){
       res.blobs[p].weight += res.blobs[k].weight;
       res.blobs.remove(k);
     }
   }

It boils down to:

   foreach(k; aa.keys) aa.remove(k);


Is it safe, or do I have to take a snapsot of the keys range like 
this? ->

   foreach(k; aa.keys.array) aa.remove(k); //this is 100% safe

I'm asking because I have no idea how the internal aa.keys range 
works. If it stores an index or a pionter inside, while I change 
the underlying structure of the aa, it could be a hazard...

Thanks in advance.


More information about the Digitalmars-d-learn mailing list