我创建了一个事件的优先级队列,该队列按Event.time排序。我插入了 5 个事件,效果很好(它们按 Event.time 的顺序排序)。但是,在我 pop() 之后,剩余的队列顺序不对(不再排序)。有人可以帮我解释为什么吗?多谢。
struct Event
{
string name;
int time;
int pid;
};
class CompareEvent
{
public:
bool operator()(Event& event1, Event& event2)
{
if (event1.time > event2.time)
return true;
return false;
}
};
主类
priority_queue<Event, vector<Event>, CompareEvent> eventList;
Event newEvent;
newEvent.name = eventName;
newEvent.time = time;
newEvent.pid = pid;
eventList.push(newEvent);
eventList.pop(); // the remaining items are not in order anymore
更新的解决方案:我调试了程序,并在调试窗口中查看了 eventList 值。不对值进行排序。但是,当 top() 时,它总是返回最低值。这些值不会在内部排序。谢谢你让我意识到这一点。
不需要对优先级队列进行排序。唯一的要求是堆属性 - 如果你调用 pop()
或 top()
,它必须返回 top 元素(给定排序函数的最低元素)。
如果需要保持元素排序的容器,请使用 std::set
或 std::map
。
如果你总是需要排序的事件,你必须排序或使用排序容器,如set或map。priority_queue仅保证 pop() 返回其中最低的元素之一(顶部)。