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

前端 未结 3 444
北荒
北荒 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:28

    I would always prefer try_emplace over emplace. A Crucial difference is that try_emplace will not construct the object associated with the key,if the key already exists.This will boost the performance in case objects of that type are expensive to create

    For example the below code (Example from https://github.com/PacktPublishing/Cpp17-STL-Cookbook/blob/master/Chapter02/efficient_insert_or_reassign_to_map.cpp)

    #include 
    #include 
    #include 
    #include 
    
    using namespace std;
    
    struct billionaire {
        string name;
        double dollars;
        string country;
    };
    
    int main()
    {
        list billionaires {
            {"Bill Gates", 86.0, "USA"},
            {"Warren Buffet", 75.6, "USA"},
            {"Jeff Bezos", 72.8, "USA"},
            {"Amancio Ortega", 71.3, "Spain"},
            {"Mark Zuckerberg", 56.0, "USA"},
            {"Carlos Slim", 54.5, "Mexico"},
            // ...
            {"Bernard Arnault", 41.5, "France"},
            // ...
            {"Liliane Bettencourt", 39.5, "France"},
            // ...
            {"Wang Jianlin", 31.3, "China"},
            {"Li Ka-shing", 31.2, "Hong Kong"}
            // ...
        };
    
        map> m;
    
        for (const auto &b : billionaires) {
            auto [iterator, success] = m.try_emplace(b.country, b, 1);
    
            if (!success) {
                iterator->second.second += 1;
            }
        }
    
    
        for (const auto & [key, value] : m) {
            const auto &[b, count] = value;
    
            cout << b.country << " : " << count << " billionaires. Richest is "
            << b.name << " with " << b.dollars << " B$\n";
        }
    }
    

    For the above code

    m.try_emplace(b.country, b, 1);
    

    if there unsuccessful insertion the pairs will not get constructed which adds to the performance

提交回复
热议问题