Getting associative array value by reference
Jesse Phillips via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Mar 31 21:56:36 PDT 2015
On Wednesday, 1 April 2015 at 03:11:58 UTC, Mark Isaacson wrote:
> I'm presently trying to create the value of a key in an
> associative array if it does not exist, and then maintain a
> reference/pointer to the value. This is what I came up with,
> but it seems really crufty and I feel that there must be a
> cleaner way:
>
> Value[string] assocArray;
>
> foreach (...) {
> auto value = key in assocArray;
> if (!value) {
> assocArray[key] = Value();
> value = &assocArray[key];
> }
> value.memberA++;
> value.memberB = "foobar";
> }
>
>
> The goal was to avoid writing:
> Value[string] assocArray;
>
> foreach (...) {
> assocArray[key].memberA++;
> assocArray[key].memberB = "foobar";
> }
>
> and save a lookup call, but my solution is both less readable
> and also performs worse for keys not already in the associative
> array...
You chopped the foreach, can I assume you solition is sooomething
like:
foreach(k, ref value; assocArray) ...
More information about the Digitalmars-d-learn
mailing list