In C++17, std::map and std::unordered_map got a new member-function template: try_emplace(). This new addition, proposed in n4279, behaves similarly to emplace(), but has th
try_emplace
also doesn't support heterogenous lookup - it can't, because it takes the key.
Suppose we have a std::map
and a std::string_view
sv
. I want to do the equivalent of ++counts[std::string(sv)];
, but I don't want to create a temporary std::string
, which is just wasteful, especially if the string is already present in the map. try_emplace
can't help you there. Instead you'd do something like
if(auto lb = counts.lower_bound(sv); lb != counts.end() && lb->first == sv) {
++lb->second;
}
else {
counts.emplace_hint(lb, sv, 1);
}