Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library


The C++ priority_queue::push function is used to add a 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. Adding a new element effectively calls push_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

void push (const value_type& val);
void push (const value_type& val);
void push (value_type&& val);

Parameters

val Specify value which need to be added in the priority_queue.

Return Value

None.

Time Complexity

Logarithmic i.e, Θ(log(n)).

Example:

In the below example, the priority_queue::push function is used to add new elements 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
  p_queue.push(100);
  p_queue.push(80);
  p_queue.push(990);
  p_queue.push(85);
  p_queue.push(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