-3
typedef std::priority_queue< Task*, std::vector< Task* > > Priority_Q;

class TaskQueue : public Priority_Q
{
public:
    TaskQueue();            

    // Queue op
    void push(Task* t){
        Priority_Q::push(t);
    }
    void pop(){
        Priority_Q::pop();
    }
}

Is it the correct way to use priority_queue. I will be pushing objects derived from Task and popping it.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Shashank89
  • 17
  • 5
  • Do you really want to inherit from the STL `priority_queue` ? Can you just make it a member variable? – hiimdaosui Jul 26 '18 at 17:58
  • I wanted to implement synchronisation between threads while pushing and popping, so i will call lock and unlock semaphores whenever push/pop is called. But, you are right, i can implement them using a memeber var also. I'll try that. – Shashank89 Jul 26 '18 at 18:00

1 Answers1

0

It should be easier to write a wrapper class and make STL priority_queue a member variable. But to make sure you set up the custom comparator for your queue, otherwise the STL data structure won't know how to order your objects. There are a couple of ways to do it. I'm just using one as example here.

If you want to add synchronization to your data structure, you can simple add internal locks and/or condition variables in your class to lock/unlock the member variable q.

class TaskQueue {
public:
    TaskQueue() {};

    bool empty() {
        return q.empty()
    }

    void push(Task* t) {
        q.push(t);
    }

    void pop() {
        if (q.empty()) {
            // You may want to do something here like throw an exception or not
        }

        // if not empty
        q.pop();
    }

    Task* top() {
        if (q.empty()) {
            // You may want to do something here like throw an exception or not
        }

        return q.top();
    }

private:
    class TaskPtrComparator {
    public:
        bool operator()(Task* t1, Task* t2) {
            // Comparison code here
        }
    };
    priority_queue<Task*, vector<Task*>, TaskPtrComparator> q;
};
hiimdaosui
  • 361
  • 2
  • 12
  • I tried this way as well.But still I am facing a weird issue. I am pushing derived class object of Task* into the Queue. top and push is working fine. But pop is not reducing size of queue. Although, I can see that the object destructor is called when i call delete on it. Next time when I call top it still returns the same address but the object is no more there. Could you please help? – Shashank89 Jul 26 '18 at 18:52
  • Add your updated code in your question. I suppose it could be the problem in your comparator. – hiimdaosui Jul 26 '18 at 19:11