In C++11 and later, std::set::emplace()builds a value in place inside the set, using the arguments you give. You do not create a temporary object first, so a copy or a move can be avoided.
Like insert(), it keeps the set sorted and unique. If an equal value already exists, the new one is thrown away. It returns a pair of an iterator and a bool. Include <set> to use it.
This is a member of std::set<T>, a sorted container of unique values. A set never keeps a duplicate and always holds its values in sorted order, so it can find, insert, and erase a value in logarithmic time. A set has no operator[] and no at(), because the value is its own key. Every element is const, so you cannot change a value through an iterator.
Syntax
Pass the arguments that the value type needs for its constructor.
C++
std::set<std::string> names;
auto r = names.emplace("Raj"); // builds the string in place
bool added = r.second; // true
std::set<std::pair<int, int>> ps;
ps.emplace(1, 2); // builds pair(1, 2)
Call
What it does
s.emplace(args...)
Builds a value from args. Returns pair<iterator, bool>.
For simple types such as int, emplace(5) and insert(5) do the same work. The benefit shows with larger types such as strings or structs. One catch is that a set may create the node before it checks for a duplicate, so a repeated value can still cost a construction.
Task has a constructor with two parameters, so emplace(2, "test") can build it directly inside the set.
The set orders tasks with operator<, which looks only at priority. The tasks sort as priority 1 then priority 2.
emplace(2, "deploy") has the same priority as "test". Neither is smaller, so the set treats them as equal and drops the new one. That is why deploy never prints.
Frequently Asked Questions
insert() takes an existing value. emplace() takes constructor arguments and builds the value inside the set. For simple types the result is the same.
C++11. It is available in every modern compiler.
No. If an equal value is already stored, the new one is discarded and the second part of the returned pair is false.
A pair. The first part is an iterator to the stored value and the second part is a bool that is true when the value was added.
Not always. For int and other small types there is no difference. It helps most with larger types where building a temporary would be costly.