I have a std::unordered_map
with a value_type that does not have a default constructor so I cannot do the following
auto k = get_key();
auto& v = my_map[k];
I ended up writing a helper function
value_type& get_value(key_type& key)
{
return std::get<0>(my_map.emplace(
std::piecewise_construct,
std::forward_as_tuple(key),
std::forward_as_tuple(args_to_construct_value)
))->second;
}
but the performance was markedly worse (i.e. the value_type's constructor showed up in perf) than the following version.
value_type& get_value(key_type& key)
{
auto it = my_map.find(key);
if (it == my_map.end())
return std::get<0>(my_map.emplace(
std::piecewise_construct,
std::forward_as_tuple(key),
std::forward_as_tuple(args_to_construct_value)
))->second;
else
return it->second;
}
I read from std::unordered_map::emplace object creation that emplace needs to construct the object in order to see if exists. But emplace is checking to see if this key value pair exists in the map before it returns.
Am I using emplace the wrong way? Is there a better pattern I should follow that:
- Won't construct my value_type every lookup (as in my first method)
- Won't do the check for to see if value_type exists in my map twice (as in my second method)
Thanks