Is there any reason to use std::map::emplace() instead of try_emplace() in C++1z?

前端 未结 3 435
北荒
北荒 2020-12-29 18:50

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

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-29 19:11

    try_emplace also doesn't support heterogenous lookup - it can't, because it takes the key.

    Suppose we have a std::map> counts; 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);
    }
    

提交回复
热议问题