www.digitalmars.com         C & C++   DMDScript  

D - associative arrays and get

reply Patrick Down <pat codemoon.com> writes:
Here is a bit of syntactic sugar that might be
nice.  When using associative arrays I often
find the need to use this pattern.

if(key in map)
{
  value = map[key];
}
else
{
  value = default;
}

This seems a little inefficient since two
lookups into map are required in the worst 
case.  The following syntax might be good.

value = map.get(key,default);


Another pattern 

if(key in map)
{
  value = map[key];
}
else
{
  map[key] = foo;
  value = foo;
}
  

Which might be stated like this.

value = map.getOrAdd(key,foo);
Jul 04 2002
next sibling parent Edgar <Edgar_member pathlink.com> writes:
I like that Idea too...


In article <Xns92416EB58DBBEpatcodemooncom 63.105.9.61>, Patrick Down says...
Here is a bit of syntactic sugar that might be
nice.  When using associative arrays I often
find the need to use this pattern.

if(key in map)
{
  value = map[key];
}
else
{
  value = default;
}

This seems a little inefficient since two
lookups into map are required in the worst 
case.  The following syntax might be good.

value = map.get(key,default);


Another pattern 

if(key in map)
{
  value = map[key];
}
else
{
  map[key] = foo;
  value = foo;
}
  

Which might be stated like this.

value = map.getOrAdd(key,foo);
Jul 04 2002
prev sibling parent reply "Sean L. Palmer" <seanpalmer earthlink.net> writes:
I'm down with that.    ;)   This is something I always find myself wanting
in STL containers, too.

Sean

"Patrick Down" <pat codemoon.com> wrote in message
news:Xns92416EB58DBBEpatcodemooncom 63.105.9.61...
 Here is a bit of syntactic sugar that might be
 nice.  When using associative arrays I often
 find the need to use this pattern.

 if(key in map)
 {
   value = map[key];
 }
 else
 {
   value = default;
 }

 This seems a little inefficient since two
 lookups into map are required in the worst
 case.  The following syntax might be good.

 value = map.get(key,default);


 Another pattern

 if(key in map)
 {
   value = map[key];
 }
 else
 {
   map[key] = foo;
   value = foo;
 }


 Which might be stated like this.

 value = map.getOrAdd(key,foo);
Jul 05 2002
parent "Walter" <walter digitalmars.com> writes:
It's the kind of pattern optimizing compilers can detect and rewrite. Good
C++ compilers recognize quite a few such patterns (you might be surprised at
how many!), but the use of the STL seems to obscure them from easy
detection.

"Sean L. Palmer" <seanpalmer earthlink.net> wrote in message
news:ag403q$lrn$1 digitaldaemon.com...
 I'm down with that.    ;)   This is something I always find myself wanting
 in STL containers, too.

 Sean
Jul 14 2002