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: 30-Jul-2019

868 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements