C++ <priority_queue> - emplace() Function
The C++ priority_queue::emplace function is used to insert new element in the priority_queue. Each insertion of element increases the priority_queue container size by one.
priority_queue is similar to a heap, where elements can be inserted in any order and max heap element is retrieved first. Using this function effectively calls emplace_back of the underlying container, and then reorders the new element to its location in the heap by calling the push_heap algorithm on the range including all the elements of the container.
Syntax
template <class... Args> void emplace (Args&&... args);
Parameters
args |
Arguments forwarded to construct the new element. |
Return Value
None.
Time Complexity
Logarithmic i.e, Θ(log(n)).
Example:
In the below example, the priority_queue::emplace function is used to insert new element in the priority_queue called p_queue.
#include <iostream> #include <queue> using namespace std; int main (){ priority_queue<int> p_queue; //add new elements in the priority queue using emplace function p_queue.emplace(100); p_queue.emplace(80); p_queue.emplace(990); p_queue.emplace(85); p_queue.emplace(10); cout<<"p_queue contains: "; while(!p_queue.empty()) { cout<<p_queue.top()<<" "; p_queue.pop(); } return 0; }
The output of the above code will be:
p_queue contains: 990 100 85 80 10
❮ C++ <priority_queue> Library