emplace vs insert in C++ STL
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.
// C++ code to demonstrate difference between // emplace and insert #include<bits/stdc++.h> 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; } |
Output:
a 24 b 25
Please refer Inserting elements in std::map (insert, emplace and operator []) for details.
Recommended Posts:
- Inserting elements in std::map (insert, emplace and operator [])
- map emplace() in C++ STL
- set::emplace() in C++ STL
- queue::emplace() in C++ STL
- priority_queue emplace() in C++ STL
- multiset::emplace() in C++ STL
- stack emplace() in C++ STL
- multimap::emplace() in C++ STL
- unordered_map emplace() in C++ STL
- deque emplace in C++ STL
- unordered_set emplace() function in C++ STL
- list emplace() function in C++ STL
- unordered_multimap emplace() function in C++ STL
- unordered_multiset emplace() function in C++ STL
- vector emplace() function in C++ STL
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



