efficient and safe way to iterate on associative array?

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Mar 4 08:46:35 PST 2016


On 3/4/16 8:53 AM, aki wrote:
> Is it okay to modify associative array while iterating it?
>
> import std.stdio;
>
> void main() {
>      string[string] hash = [ "k1":"v1", "k2":"v2" ];
>      auto r = hash.byKeyValue();
>      while(!r.empty) {
>          auto key = r.front.key;
>          auto value = r.front.value;
>          r.popFront();
>          writefln("key=%s, value=%s", key, value);
>          // may not modify 'hash' here ?
>          hash = null;
>      }
> }
>
> I guess probably it's not.
> Then, my question is are there an efficient and safe way to iterate on
> an associative array even if there are possibility to be modified while
> iterating?
> I'm writing interpreter and want to make my language to be safe; even
> malicious script cannot fall it in 'core dump' state. It is okay if it
> causes undefined behavior like throw or instant exit from loop, but not
> crash.
>
> Thanks, Aki.
>

You cannot add or remove keys. You can modify values for existing keys.

Note, in your code, this would not cause a problem, since setting hash 
to null just removes the reference from the local variable 'hash', it 
does not alter the AA in any way.

In dcollections, all containers support "purging", or iterating through 
elements, removing the current element if desired before moving to the 
next. But I haven't touched this library in ages, I don't know if it 
still compiles even.

-Steve


More information about the Digitalmars-d-learn mailing list