Emplace vs Insert in C++ STL



emplace operation avoids unnecessary copy of object and does the insertion more efficiently than insert operation. Insert operation takes a reference to an object.

Algorithm

Begin
   Declare set.
   Use emplace() to insert pair.
   Use insert() to insert pair by using emplace().
   Print the set.
End

Example Code

#include<bits/stdc++.h>
using namespace std;
int main() {
   set<pair<int, char>> s;
   s.emplace(7, 'a');
   s.insert(make_pair(6, 'b'));
   for (auto it = s.begin(); it != s.end(); ++it)
      cout << " " << (*it).first << " " << (*it).second << endl;
   return 0;
}

Output

7 a
6 b
Updated on: 2019-07-30T22:30:25+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements