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

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

  1. cool_guy

    cool_guy New Member

    Nov 11, 2010
    Likes Received:
    Trophy Points:
    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
  2. xpi0t0s

    xpi0t0s Mentor

    Aug 6, 2004
    Likes Received:
    Trophy Points:
    Senior Support Engineer
    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.

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice