emplace vs insert in C++ STL

C++Server Side ProgrammingProgramming

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
raja
Published on 01-Apr-2019 09:32:02
Advertisements