Is remove safe using foreach

Steven Schveighoffer schveiguy at gmail.com
Mon Dec 12 17:29:00 UTC 2022


On 12/12/22 12:23 PM, lili wrote:
> ```
> int[string] aa = ["ok":1, "aaa":2, "ccc":3, "ddd":4];
>      foreach (k ; aa.byKey)
>      {
>          if (k == "aaa") {
>          aa.remove(k);
>          aa["ww"] = 33;
>          }
> 
>          if (k == "ww") {
>          aa.remove(k);
>          aa["vv"] = 33;
>          }
>      }
> 
> writeln(aa); // output ["ok":1, "ddd":4, "vv":33, "ccc":3] is ok
> ```
> 

Removing keys while iterating is not supported. It will break, in 
confusing ways, and possibly include a null pointer dereference.

Instead, either iterate over `aa.keys`, which makes a copy of the keys 
into an array, store the keys to remove for later processing, or 
construct a new AA with the indicated keys removed.

-Steve


More information about the Digitalmars-d-learn mailing list