Associative Array of structs

Denis Koroskin 2korden at gmail.com
Wed Dec 3 01:36:00 PST 2008


03.12.08 в 03:55 Jarrett Billingsley в своём письме писал(а):

> On Tue, Dec 2, 2008 at 7:34 PM, Zane <zane.sims at gmail.com> wrote:
>> I tried writing to an associative array and got the exception:
>>
>> tango.core.Exception.ArrayBoundsException at test(15): Array index out of  
>> bounds
>>
>> the program below causes the exception:
>>
>> module test;
>>
>> import tango.io.Stdout;
>> import tango.io.Console;
>>
>> struct S {uint i;}
>>
>> int main()
>> {
>>        S[char[]] s;
>>
>>        s["test"].i = 1;
>>
>>        Stdout.format("Done!").flush;
>>
>>        return 0;
>> }
>>
>> But the program below works fine:
>>
>> module test;
>>
>> import tango.io.Stdout;
>> import tango.io.Console;
>>
>> struct S {uint i;}
>>
>> int main()
>> {
>>        S[char[]] s;
>>
>>        S t;
>>        t.i = 1;
>>
>>        s["test"] = t;
>>
>>        Stdout.format("Done!").flush;
>>
>>        return 0;
>> }
>>
>> Am I supposed to be able to do both methods, or is the second the only  
>> possible way?  Some explanation would be very helpful.
>
> Only the second is legal.  The first is doing something like this:
>
> auto temp = &s["test"];

Correction:
auto temp = "test" in s;

> temp.i = 1;
>
> Of course, you haven't added anything to s yet, so s["test"] fails
> with an out-of-bounds error.
>
> It's a little awkward, and in fact long ago, AAs used to implicitly
> add items when accessing undefined indices (but many people found that
> unintuitive and the behavior was changed to what it is now).
>
> It's not too much work to make an AA wrapper struct which overloads
> opIndex[Assign] and allows you to do this, by adding key-value pairs
> if they don't already exist.



More information about the Digitalmars-d mailing list