On Friday, 4 March 2016 at 13:53:22 UTC, 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.
I think what you can do is extract its contents to an array,
iterate it and modify it as you like, and then insert back to
another associative array. I don't think it's efficient but I
don't know if it's possible to do something else.