Assosiative array pop

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jun 25 02:55:43 PDT 2014


On Wednesday, June 25, 2014 09:30:48 seany via Digitalmars-d-learn wrote:
> Given an assosiative array : int[string] k, is there a way
> (either phobos or tango) to pop the first element of this array
> and append it to another array?
>
> I can come up with a primitive soluiton:
>
> int[string] k;
> // populate k here
>
> int[string] j;
>
>
> foreach(sttring key, int val; k)
> {
>
> j[key] = val;
> break;
> }
>
> but could it be better? it is wroth noting that the keys are not
> known beforehand.

There's no such thing as the "first" element of an AA. An associative array is
a hash table and has no order to it. The order you get when iterating with
foreach is undefined. If you just want to get _a_ key from an AA, then you
need to either iterate over it with foreach and then break like you're doing
or use byKey to get a range. e.g. something like

auto key = k.byKey().front;
j[key] = k[key];

should work. But there is no "first" key, so I don't know really understand
what you're really trying to do here and can't provide a better answer without
more information.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list