C++ Standard Library C++ STL Library

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 example below, the priority_queue::emplace function is used to insert new element in the priority_queue called pqueue.

#include <iostream>
#include <queue>
using namespace std;
 
int main (){
  priority_queue<int> pqueue;
  
  //add new elements in the priority queue using emplace function
  pqueue.emplace(100);
  pqueue.emplace(80);
  pqueue.emplace(990);
  pqueue.emplace(85);
  pqueue.emplace(10);

  cout<<"pqueue contains: ";
  while(!pqueue.empty()) {
   cout<<pqueue.top()<<" "; 
   pqueue.pop();  
  }
  return 0;
}

The output of the above code will be:

pqueue contains: 990 100 85 80 10 

❮ C++ <queue> Library