# priority_queue::push() in C++

Sign up for FREE 1 month of Kindle and read all our books for free.

Get FREE domain for 1st year and build your brand new site

Note : if you are not familiar with what is a priority queue or how to initialize it, I suggest you to first have a look at this article:

Initialize Priority Queue in C++## Push Function in priority Queue

Push function in priority queue is used to to insert a element in the queue, the element is inserted in the priority queue based on it's value which defines it's priority in the queue.

## Position based on priority

If the element is inserted in priority queue is based on max heap then higher the value of the element in the queue the more it will be nearer to the top of queue. If the value of the element is highest in the priority queue then element is inserted at the top of the priority queue.

if the element is inserted in the priority queue based is on min heap then lower the value of the element in the queue the higher it will be on the priority queue. if the value of element is lowest in the whole queue then it's inserted at the top.

Priority queue uses min heap or max heap in implementation -

## Syntax

Syntax for push function in priority_queue is -

```
priority_queue<int> pq ;
int x = 10 ;
pq.push(x) ;
// above line represents syntax for pushing element in the queue.
```

## Code

Push function in priority queue based on min heap and max heap.

```
#include<iostream>
#include<queue>
// don't forget to include queue in your code otherwise code below will give error
using namespace std ;
int main(){
priority_queue<int> pq ;
// priority queue based on max heap
pq.push(7) ;
pq.push(6) ;
pq.push(15) ;
pq.push(10) ;
pq.push(12) ;
pq.push(17) ;
// using the push function in pq
priority_queue<int,vector<int> ,greater<int>> pq2;
// priority queue based on min heap
pq2.push(7) ;
pq2.push(6) ;
pq2.push(15) ;
pq2.push(10) ;
pq2.push(12) ;
pq2.push(17) ;
// using the push function in pq2
cout<<"priority queue based on max heap:\n" ;
while( pq.size() ){
cout<<pq.top()<<endl;
pq.pop() ;
}
cout<<"priority queue based on min heap:\n" ;
while( pq2.size() ){
cout<<pq2.top()<<endl;
pq2.pop() ;
}
return 0 ;
}
```

## Output

```
priority queue based on max heap:
17
15
12
10
7
6
priority queue based on min heap:
6
7
10
12
15
17
```

## Question

To make sure you understand the article properly make sure you answer this queshion