C++ set - emplace() Function
The C++ set::emplace function is used to insert a new unique element in the set. The insertion of new element happens only when it is not already present in the set. If insertion happens, it increases the size of the set by one. As a set is an ordered data container, hence it stores the new element in its respective position to keep the set sorted.
Syntax
template <class... Args> pair<iterator,bool> emplace (Args&&... args);
Parameters
args |
Arguments forwarded to construct the new element. |
Return Value
For successfully inserted element, returns a pair of an iterator pointed to newly added element and a value of true. Otherwise, returns a pair of an iterator pointed to equivalent element and a value of false.
Time Complexity
Logarithmic i.e, Θ(log(n)).
Example:
In the example below, the set::emplace function is used to insert new element in the set called MySet.
#include <iostream> #include <set> using namespace std; int main (){ set<int> MySet{10, 20, 30, 40, 50}; //insert a new unique element in the set auto NewInsert = MySet.emplace(60); if(!NewInsert.second) cout<<"60 is already present in MySet.\n"; else cout<<"60 is added in MySet.\n"; //insert an already present element in the set NewInsert = MySet.emplace(10); if(!NewInsert.second) cout<<"10 is already present in MySet.\n"; else cout<<"10 is added in MySet.\n"; return 0; }
The output of the above code will be:
60 is added in MySet. 10 is already present in MySet.
❮ C++ <set> Library