In C++, all containers (vector, stack, queue, set, map, etc) support both insert and emplace operations.
Both are used to add an element in the container.
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.
CPP
#include<bits/stdc++.h>
using namespace std;
int main()
{
multiset<pair< char , int >> ms;
ms.emplace( 'a' , 24);
ms.insert(make_pair( 'b' , 25));
for ( auto it = ms.begin(); it != ms.end(); ++it)
cout << " " << (*it).first << " "
<< (*it).second << endl;
return 0;
}
|
Output:
a 24
b 25
Time Complexity: The time complexity depends upon the type of the container. Both the operations have same time complexity.
Vector: O(1)
Priority Queue: O(log n)
Set: O(log n)
map: O(log n)
Please refer Inserting elements in std::map (insert, emplace and operator []) for details.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
14 Jun, 2022
Like Article
Save Article