Declaring priority queue?

When we declare a std::priority_queue,why do we sometime type priority_queue<int, vector<int>, greater<int> > q, other time we type priority_queue<int> q. Can anyone explain what does priority_queue<int, vector<int>, greater<int> > mean and why do we declare like that?

1 Like

The third template parameter greater in above declaration of priority queue is used as the Comparator function object for the queue, checking whether the LHS value is greater than the RHS value. You can write your own comparison class according to the task you want to compute like,

class ComparisonClass {
    bool operator() (Node, Node) {
        //comparison code here

then, you can declare your priority queue as :

priority_queue$<Node, vector<Node>, ComparisonClass>$ queue;

Priority queues uses encapsulated object of a specific container class as its underlying container,
and type of that underlying container object is where the elements are stored, which can either be
vector$<int> or vector< pair<int,int>

>$ etc. and if no container class is specified (eg., priority_queue$<$int$>$ q) then, default container *vector* is used.
1 Like

Why is there vector template in std::priority_queue and if just type priority_queue what is the difference?

1 Like

@pkien I’ve updated the answer, hope it clears your doubt.