efficient and safe way to iterate on associative array?

Mike Parker via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Mar 4 08:29:51 PST 2016


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.

It is not safe to modify an aa when iterating with .byKey, 
.byValue, or .byKeyValue. You can safely do it with .keys and 
.values, but these allocate so it isn't likely to be the most 
efficient. Your best bet if it's something you need to do 
frequently is probably what JR recommended.



More information about the Digitalmars-d-learn mailing list