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

Discussion in 'C' started by cool_guy, Nov 11, 2010.

1. ### cool_guyNew Member

Joined:
Nov 11, 2010
Messages:
1
0
Trophy Points:
0
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:
Code:
```bool operator<(const MyPQ &A,MyPQ &B){return A.getData() < B.getData() }
```
So if I give the values,

Code:
```#include "PQ.h"
int main()
{
MyPQ<int> pq;

pq.push(2);
pq.push(5);
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

2. ### xpi0t0sMentor

Joined:
Aug 6, 2004
Messages:
3,012
203
Trophy Points:
0
Occupation:
Senior Support Engineer
Location:
England
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 likes this.