In C++11, emplace() adds a new element to a std::priority_queue by building it inside the queue. You pass the constructor arguments, not a finished object, and the queue creates the element itself.
This is handy for pairs, tuples, and structs. Instead of pq.push(std::make_pair(3, "low")) you write pq.emplace(3, "low"). The result is the same: the new element is placed by priority, and top() still gives the highest one.
This function is a member function of std::priority_queue<T>, declared in the <queue> header. It needs C++11 or newer (-std=c++11). You call it with a dot, for example pq.emplace(...).
Syntax
Give emplace() the arguments for the constructor of the element type. It needs C++11 or newer.
C++
std::priority_queue<std::pair<int, std::string>> pq;
pq.emplace(2, "write"); // builds pair<int, string>(2, "write")
pq.emplace(8, "deploy");
auto best = pq.top(); // {8, "deploy"}
Call
What it does
pq.emplace(args...)
Builds a new element from args inside the queue, then restores the heap order.
emplace() returns nothing and takes O(log n) time, like push(). The arguments must match a constructor of the element type. For simple types such as int, push() and emplace() behave the same.
Library declarations
C++
template<class... Args>
void emplace(Args&&... args); // C++11
// priority_queue<T, Container, Compare> from <queue>
// It calls c.emplace_back(std::forward<Args>(args)...)
// and then std::push_heap(...).
Parameters
Parameter
Description
args...
Zero or more arguments that are passed to the constructor of the element type T. The queue builds the new element from them.
Return Value
Return Value
Description
Nothing
emplace() returns void.
C++ Examples
Example 1 — Emplace Pairs Without make_pair
The first value of a pair is the priority. Pass both values straight to emplace().
using Item = std::pair<int, int> gives the pair a short name. The queue type adds std::greater<Item> to make a min-heap.
emplace(7, 1) and the next two calls build the pairs in place. The pair with the smallest distance is kept on top.
The loop prints the shortest distance first: 3, 5, 7. Each pop() reveals the next smallest pair.
Frequently Asked Questions
It builds a new element inside the priority queue from constructor arguments, then restores the heap order. The highest-priority element is still on top.
push() takes a finished object. emplace() takes the constructor arguments and builds the object in place, which can save a copy or a move. For plain numbers they behave the same.
emplace() was added in C++11. Every modern compiler supports it. Compile with -std=c++11 or newer.
No. For priority_queue it returns void. You read the top element later with top().
Yes. Create the queue with std::greater, for example std::priority_queue<std::pair<int,int>, std::vector<std::pair<int,int>>, std::greater<std::pair<int,int>>>, and call emplace() as usual.