How To Use (Operator < )Method In My Priority Queue class

cool_guy's Avatar
Newbie Member
Hi, I am new to c++. I want to create user-defined Priority Queue class. So my problem is how can I use comparison operator (operator < ) in my priority class.

Ex I have:
bool operator<(const MyPQ &A,MyPQ &B){return A.getData() < B.getData() }
So if I give the values,

#include "PQ.h"
int main()
 MyPQ<int> pq;

 return 0;

A.getData() should be 2 and B.getData() should be 5
then if I call pop method, the highest priority element should remove. Please give me advice how can I use operator < method for that purpose, I am trying is for 2 days but no luck
xpi0t0s's Avatar, Join Date: Aug 2004
You need to think this through a bit more. A queue (whether priority or otherwise) will most likely contain multiple values so you can't simply do "A.getData() < B.getData()".

operator< takes two queues, but your code only defines one (pq). You could start - after thinking it through, that is - by defining TWO queues.

What you need to think through is this: what exactly do you want operator< to do?

To answer your question probably you'll need to sort the queue by priority (althoough you need to know what defines the priority). You can use operator< for sorting. Then popping the highest priority event off the queue will be a simple case of popping off the item at whichever end contains the highest priority item.

If you don't want to sort the queue by priority, then you will have to use operator< to identify the item with the highest priority, keeping track of which one it is as you loop over the queue, so that you can determine which item to remove from the array.
cool_guy like this