Inserting into an Associative array?

Go To


I'm playing around with associative arrays right now and I can't seem to figure out how to add additional objects to the array. I tried insert but it doesn't recognize both arguments.

Also, if I do this it produces an error:

Node[bool] test;

Node node;

Node[bool] temp = [ false:node ];

test ~= temp;

//Error 1   Error: cannot append type Node[bool] to type
//Node[bool]    C:\Users\CP\Documents\Visual Studio
//2010\Projects\D\STDS\NPC.d    256 

Does this mean you can't use the append operator on associative arrays ?

2012-04-04 18:50
by RedShft
With bool keys you do not have many options... : - DejanLekic 2012-04-04 21:36


To add a single element, just assign it like you would for any other type of array.

test[false] = node;

To append an assoc array to another assoc array, loop over it, and reassign the elements.

foreach(k, v; temp) test[k] = v;

The why: Associative arrays are not lists; as the name suggests, they are, well, associative arrays. The append operator would make sense for consecutive list of elements. D's AAs are hash tables.

2012-04-04 18:54
by q66
All I want to do is add one element. How would I do that - RedShft 2012-04-04 18:54
Then use the assignment op: assoc_array[key] = value - q66 2012-04-04 18:57


Are you looking for an array of associative arrays? In that case, the following would work, as an example:

struct Node { int x; }
Node[bool][] test;
Node[bool] temp = [ false:Node(1), true:Node(2) ];
test ~= temp;
test ~= [ false:Node(3), true:Node(4) ];
writefln("Nodes: %s", test); // Nodes: [[false:Node(1), true:Node(2)], [false:Node(3), true:Node(4)]]

Which would give you a linear array (test), each element of which is an associative array with a maximum of two elements (since your key type is bool).

However, are you trying to create a binary tree instead? Then you'd want Node member variables inside the Node struct itself for the left and right branches (please disregard if this isn't the case).

2012-04-05 17:25
by ccjuju