Accessing contents of associative arrays in an optimal way

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jul 9 13:42:53 PDT 2016


On 07/09/2016 01:32 PM, phant0m wrote:
 > Suppose I have AA of structures:
 >
 > struct Foo {
 >      int value;
 >      string name;
 > }
 >
 > Foo[int] records;
 >
 > 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";

Yes, two searches. Although it is slower, it's still O(1). :)

 > How can I access elements of this AA by a "reference"?

The 'in' operator returns a pointer to the element:

import std.stdio;

struct Foo {
      int value;
      string name;
}

void main() {
     Foo[int] records;
     records[3] = Foo(42, "hello");

     if (auto record = 3 in records) {
         record.value = 10;
         record.name = "name";
     }

     writeln(records);
}

Ali



More information about the Digitalmars-d-learn mailing list