MD. Khairul Basar
MD. Khairul Basar

Reputation: 5110

Understanding operator() overloading with min stl priority_queue

i have been studying on priority_queue. when i tried to create a min stl priority_queue, i searched on net and found some tutorial. but i don't understand a few things in the code. so far i have the following code.

#include<cstdio>
#include<iostream>
#include<queue>
using namespace std;
class compare
{
public:
    bool operator()(const int &a, const int &b)
    {
        return a>b;
    }
};
int main()
{
    priority_queue<int, vector<int>, compare > pq;
    int i,n;
    for(i=1;i<=10;i++)
    {
        pq.push(i);
    }
    while(!pq.empty())
    {
        cout<<pq.top()<<endl;
        pq.pop();
    }
    return 0;
}

questions:

  1. in the operator function there are two parameters but, when i push element in the queue there is only 1 argument then how this works and compare ?
  2. what does the declaration of pq mean ? i mean why there is <vector<int>> and what does it mean and do ?

Upvotes: 1

Views: 567

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254461

in the operator function there are two parameters but, when i push element in the queue there is only 1 argument then how this works and compare ?

The comparator is used by the priority queue to compare elements to determine which has the higher priority. When you push an element, it compares it with elements already in the queue to determine where to position the new element.

In this case, the comparator says that the element with the greater value has the greater priority.

what does the declaration of pq mean ? i mean why there is <vector<int>> and what does it mean and do ?

priority_queue is a container adapter. It uses a container for storage, and adds extra functionality - in this case, extraction in priority order. vector<int> specifies that it should use a vector as its storage; that's the default, and you should use that unless you have a good reason not to.

Upvotes: 2

Related Questions