I’m using the STL map data structure, and at the moment my code first invokes find(): if the key was not previously in the map, it calls insert() it, otherwise it does nothing.
map<Foo*, string>::iterator it;
it = my_map.find(foo_obj); // 1st lookup
if(it == my_map.end()){
my_map[foo_obj] = "some value"; // 2nd lookup
}else{
// ok do nothing.
}
I was wondering if there is a better way than this, because as far as I can tell, in this case when I want to insert a key that is not present yet, I perform 2 lookups in the map data structures: one for find(), one in the insert() (which corresponds to the operator[] ).
Thanks in advance for any suggestion.
Normally if you do a find and maybe an insert, then you want to keep (and retrieve) the old value if it already existed. If you just want to overwrite any old value,
map[foo_obj]="some value"will do that.Here’s how you get the old value, or insert a new one if it didn’t exist, with one map lookup:
This is a common enough idiom that you may want to use a helper function:
If you have an expensive computation for v you want to skip if it already exists (e.g. memoization), you can generalize that too:
where e.g.
If the mapped type isn’t default constructible, then make F provide a default value, or add another argument to get_else_compute.