insert vs emplace vs operator[] in c++ map

前端 未结 5 1569
星月不相逢
星月不相逢 2020-11-29 14:33

I\'m using maps for the first time and I realized that there are many ways to insert an element. You can use emplace(), operator[] or insert(

5条回答
  •  鱼传尺愫
    2020-11-29 15:17

    Apart from the optimisation opportunities and the simpler syntax, an important distinction between insertion and emplacement is that the latter allows explicit conversions. (This is across the entire standard library, not just for maps.)

    Here's an example to demonstrate:

    #include 
    
    struct foo
    {
        explicit foo(int);
    };
    
    int main()
    {
        std::vector v;
    
        v.emplace(v.end(), 10);      // Works
        //v.insert(v.end(), 10);     // Error, not explicit
        v.insert(v.end(), foo(10));  // Also works
    }
    

    This is admittedly a very specific detail, but when you're dealing with chains of user-defined conversions, it's worth keeping this in mind.

提交回复
热议问题