Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   How To Use (Operator < )Method In My Priority Queue class (http://www.go4expert.com/forums/operator-method-priority-queue-class-t23840/)

cool_guy 11Nov2010 13:13

How To Use (Operator < )Method In My Priority Queue class
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 :embarasse:embarasse:embarasse

xpi0t0s 12Nov2010 22:26

Re: How To Use (Operator < )Method In My Priority Queue class
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.

All times are GMT +5.5. The time now is 09:11.