Accessing contents of associative arrays in an optimal way

ag0aep6g via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jul 9 13:48:27 PDT 2016


On 07/09/2016 10:32 PM, phant0m wrote:
> As far as I know, AA implemented as a hashtable. So, will there be two
> searches performed (one search for each line)?
> records[3].value = 10;
> records[3].name = "name";

Yup. A good optimizer may be able to eliminate one, but conceptually 
there are two lookups.

> How can I access elements of this AA by a "reference"? In C++ I can use
> reference to an element of the map:
> Foo& foo = records.find(3).second;
> foo.value = 10;
> foo.name = "name";

You can take the address of `records[3]`:

----
Foo* foo = &records[3];
foo.value = 10;
foo.name = "name";
----

If `records[3]` may be not set, you can use `3 in records` to get a 
pointer to the value or null if the key isn't set:

----
Foo* foo = 3 in records;
if (foo is null) {records[0] = Foo.init; foo = 3 in records;}
foo.value = 10;
foo.name = "name";
----


More information about the Digitalmars-d-learn mailing list