best idiom for insert if not present; else use value in assoc array

Jonathan M Davis jmdavisProg at gmx.com
Thu Feb 7 12:36:00 PST 2013


On Thursday, February 07, 2013 21:20:46 Dan wrote:
> For an associative array, what is the best idiom that allows for
> checking if a key exists in the AA. If it does do something with
> the value, if not initialize the value and then do something with
> it.
> 
> In this code: http://dpaste.dzfl.pl/daab318f
> 
> How would this piece be improved? It looks like it would have to
> perform the hash and do a find 3 times:
> 
> auto exists = (k in _dataMap);
> if(!exists) {
> _dataMap[k] = init;
> exists = (k in _dataMap);
> }
> ... use *exists
> 
> At a higher level and assuming the general goal of this basic
> struct is clear, any other suggestions welcome.
> 
> Also, an FYI to dpaste maintainer that the compiler service has
> been unavailable for a while.

Remove the useless parens around the in expression. :)

Seriously though, I believe that you're pretty much doing it exactly as its 
supposed to be done, except that you can avoid some of the extra overhead if 
don't need to refer to the actual element in the AA. If that's the case, you 
can do

T var;

if(auto found = k in _dataMap)
 var = *found;
else
{
 var = init;
 _dataMap[k] = var;
}

//...use var

Of course, if assigning T is expensive enough, that could actually be more 
expensive than your example, since an extra assignment is required.

Or, if you didn't care about actually putting it in the AA, you could use the 
get function.

auto var = _dataMap.get(k, init);

But I certainly agree that it would be nice if there were a function that 
inserted the element if it wasn't already there and then returns it regardless 
of whether it was there or not. I don't think that such a function exists 
though.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list