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
You can simply "insert-or-overwrite" with the standard insert
function:
auto p = mymap.insert(std::make_pair(key, new_value));
if (!p.second) p.first->second = new_value; // overwrite value if key already exists
If you want to pass the elements by rerference, make the pair explicit:
insert(std::pair(key, value));
If you have a typedef for the map like map_t
, you can say std::pair
, or any suitable variation on this theme.
Maybe this is best wrapped up into a helper:
template
void insert_forcefully(Map & m,
typename Map::key_type const & key,
typename Map::mapped_type const & value)
{
std::pair p = m.insert(std::pair(key, value));
if (!p.second) { p.first->second = value; }
}