I’ve got a value type that I want put into a map.
It has a nice default copy constructor, but does not have a default constructor.
I believe that so long as I stay away from using operator[] that everything will be OK.
However I end up with pretty ugly constructs like this to actually insert an object.
(I think insert just fails if there is already a value for that key).
// equivalent to m[5]=x but without default construction
std::map<int,X>::iterator it = m.find(5);
if( it != m.end() )
{
m->second = x;
}
else
{
m->insert( std::make_pair(5,x) );
}
Which I believe will scan the map twice, and also looks pretty ugly.
Is there a neater / more efficient way to do this?
You can simply “insert-or-overwrite” with the standard
insertfunction:If you want to pass the elements by rerference, make the pair explicit:
If you have a typedef for the map like
map_t, you can saystd::pair<map_t::key_type &, map_t::mapped_type &>, or any suitable variation on this theme.Maybe this is best wrapped up into a helper: