c++ ordered(stable) priority queue

感情迁移 提交于 2019-12-02 00:35:58

问题


I am implementing a toy scheduler which reads a input file of process specifications such as arrival time, total run time and then schedules the process based on random io/cpu bursts.

The file is of the format

Arrival time, total CPU time, CPU burst, IO Burst.

Now, when there are two process with same arrival time, the scheduler have to schedule the process first the process which is mentioned first in the file.

I am keeping the entries in the file in a priority queue.

struct EventComparator{
  bool operator()(const Event* event1, const Event* event2){
    return event1->getTimestamp() >= event2->getTimestamp();
  }   
};  
priority_queue<Event*, vector<Event*>, EventComparator> eventQueue;

where Event is just an object encapsulating the process parameters.

My problem is, the priority queue is not stable. By stable I mean that the order of the process gets reversed.

Suppose the input file has

60 200 5 20

60 20 10 10

40 100 10 40

0 200 40 90

If i pop from the priority queue, I expect Line4, line 3, Line1 and then Line2. But I get Line4, Line3, Line2, Line1.

My question is, what can I do to get a stable priority queue?


回答1:


  1. Your comparator is incorrect. The documentation for the std::priority_queue states that it should provide a strict weak ordering(that is, it should event1->getTimestamp() > event2->getTimestamp(), not >=).

  2. To make it stable, you can just store the line number inside the Event and compare it if event1->getTimestamp() == event2->getTimestamp().

Something like this:

struct EventComparator {
  bool operator()(const Event* event1, const Event* event2) {
    if (event1->getTimestamp() != event2->getTimestamp()) {
      return event1->getTimestamp() > event2->getTimestamp();
    }
    return event1->getLineNumber() > event2->getLineNumber();
  }   
};  


来源:https://stackoverflow.com/questions/28836251/c-orderedstable-priority-queue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!