Hash Tables in D

Bastiaan Veelo via Digitalmars-d-announce digitalmars-d-announce at puremagic.com
Mon Jan 4 00:06:01 PST 2016


On Monday, 4 January 2016 at 07:09:30 UTC, Minas Mina wrote:
> On Sunday, 3 January 2016 at 19:29:05 UTC, Martin Nowak wrote:
>>
>> There is a bug.
>>
>> You should never do this b/c of iterator/range invalidation.
>>
>> foreach (key; aa.keys)
>>     aa.remove(key);
>
> The reference states that keys: "Returns dynamic array, the 
> elements of which are the keys in the associative array".
>
> Isn't the array newly allocated?


Hi,

You are right:

> void main()
> {
> 	import std.stdio;
> 	int[int] aa;
> 	foreach (i; 0..9)
> 		aa[i] = i * 10;
> 	writeln(aa); // [0:0, 6:60, 7:70, 2:20, 3:30, 1:10, 8:80, 
> 5:50, 4:40]
> 
> 	foreach (key; aa.keys)
> 		aa.remove(key);
> 	writeln(aa); // []
> }

This would be a bug (segfault on my machine):

> 	foreach (key; aa.byKey)
> 		aa.remove(key);

Note that, in this example, there is no need to remove every 
element separately, you can also just do

> void main()
> {
> 	import std.stdio;
> 	int[int] aa;
> 	foreach (i; 0..9)
> 		aa[i] = i * 10;
> 	writeln(aa); // [0:0, 6:60, 7:70, 2:20, 3:30, 1:10, 8:80, 
> 5:50, 4:40]
> 
> 	aa = null;
> 	writeln(aa); // []
> }

Bastiaan.


More information about the Digitalmars-d-announce mailing list