Thread overview | |||||
---|---|---|---|---|---|
|
April 01, 2015 Getting associative array value by reference | ||||
---|---|---|---|---|
| ||||
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... |
April 01, 2015 Re: Getting associative array value by reference | ||||
---|---|---|---|---|
| ||||
Posted in reply to Mark Isaacson | 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) ...
|
April 01, 2015 Re: Getting associative array value by reference | ||||
---|---|---|---|---|
| ||||
Posted in reply to Jesse Phillips | Not quite. You'll note that I am creating the elements in the associative array, not just iterating over them; some of them just happen to be duplicates. FWIW: That foreach happens to be over an input stream. |
Copyright © 1999-2021 by the D Language Foundation