Thread overview
associative arrays and get
Jul 04, 2002
Patrick Down
Jul 04, 2002
Edgar
Jul 05, 2002
Sean L. Palmer
Jul 15, 2002
Walter
July 04, 2002
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);


July 04, 2002
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);
>
>


July 05, 2002
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);



July 15, 2002
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