Are associative arrays stable in D?
Jonathan M Davis
jmdavisProg at gmx.com
Tue Jul 16 12:54:18 PDT 2013
On Tuesday, July 16, 2013 21:37:13 Gary Willoughby wrote:
> Are associative arrays stable in D? I have to ask because i'm
> having a great deal of problems with them for simple operations.
> For example the following crashes.
>
> import std.stdio;
>
> void main(string[] args)
> {
> int[string] waiting;
>
> waiting["gary"] = 1;
> waiting["tess"] = 2;
>
> foreach (string key; waiting.byKey())
> {
> writeln(key);
> writeln(waiting[key]);
> waiting.remove(key);
> }
> }
>
> If however you remove the .byKey() call and use .keys instead, it
> works!
>
> Also if you remove the 'writeln(waiting[key]);' line from the
> above code it prints about 40 blank lines.
It's not safe to remove anything from the AA while iterating over it. Doing so
will invalidate the range. If you did
foreach(auto key; waiting.keys())
{
writeln(key);
writeln(waiting[key]);
waiting.remove(key);
}
then you'd be okay - either that or create a new array which you append the
keys to that you want to remove and then have a second loop which loops over
that array and removes each of the keys from the AA. In this particular case,
since you're removing everything, it's probably more efficient to just allocate
the array with all of them up front with keys(), but if you were only removing
some of them, then it would probably be more efficient to create an array of the
keys to remove and then iterate over those in a second loop.
- Jonathan M davis
More information about the Digitalmars-d-learn
mailing list