priority_queue::push() method

A priority queue is a dynamically resizing container adopter in the C++ Standard Library. Elements in a priority queue are arranged in non-decreasing order such that the first element is always the greatest element in the queue. The priority_queue::push() is a method available in the STL which inserts a new element to the priority queue.

Syntax:

priorityq_name.push(val);

Parameter: The priority_queue::push() accepts a single parameter:
•The value that has to be added to the container

Return value: none

Example of priority_queue::push() method

#include <iostream>>
#include <queue>

using namespace std;

int main ()
{
    priority_queue<int> q;

    q.push(10);  // inserts 10 to queue, top = 10
    cout<<"Top: "<<q.top()<<endl;
    q.push(20);  // inserts 20 to queue, top = 20 (largest element)
    cout<<"Top: "<<q.top()<<endl;
    q.push(40);  // inserts 40 to queue, top = 40
    cout<<"Top: "<<q.top()<<endl;
    q.push(30);  // inserts 30 to queue, top is still 40
    cout<<"Top: "<<q.top()<<endl;

    return 0;
}

Output:

Top: 10
Top: 20
Top: 40
Top: 40

This article is written by

Please comment below, if you have any doubts or find any error in the above article.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top