digitalmars.D.learn - Getting associative array value by reference
- Mark Isaacson (24/24) Mar 31 2015 I'm presently trying to create the value of a key in an
- Jesse Phillips (4/28) Mar 31 2015 You chopped the foreach, can I assume you solition is sooomething
- Mark Isaacson (4/4) Mar 31 2015 Not quite. You'll note that I am creating the elements in the
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...
Mar 31 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) ...
Mar 31 2015
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.
Mar 31 2015