www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Getting associative array value by reference

reply "Mark Isaacson" <turck11 hotmail.com> writes:
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
parent reply "Jesse Phillips" <Jesse.K.Phillips+D gmail.com> writes:
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
parent "Mark Isaacson" <turck11 hotmail.com> writes:
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