Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

emplace vs insert in C++ STL

  • Difficulty Level : Medium
  • Last Updated : 25 May, 2018

In C++, all containers (vector, stack, queue, set, map, etc) support both insert and emplace operations.

The advantage of emplace is, it does in-place insertion and avoids an unnecessary copy of object. For primitive data types, it does not matter which one we use. But for objects, use of emplace() is preferred for efficiency reasons.

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

// C++ code to demonstrate difference between
// emplace and insert
using namespace std;
int main()
    // declaring map
    multiset<pair<char, int>> ms;
    // using emplace() to insert pair in-place
    ms.emplace('a', 24);
    // Below line would not compile
    // ms.insert('b', 25);    
    // using emplace() to insert pair in-place
    ms.insert(make_pair('b', 25));    
    // printing the multiset
    for (auto it = ms.begin(); it != ms.end(); ++it)
        cout << " " << (*it).first << " "
             << (*it).second << endl;
    return 0;


 a 24
 b 25

Please refer Inserting elements in std::map (insert, emplace and operator []) for details.

My Personal Notes arrow_drop_up
Recommended Articles
Page :