C++ 中的优先级队列在 pop() 之后顺序不正确
Priority queue in C++ is out of order after pop()
我创建了一个事件的优先级队列,该队列按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() 返回其中最低的元素之一(顶部)。
相关文章:
- 为什么在popback()操作之后,它仍然打印完整的矢量
- CMake-按正确顺序将项目与C运行时对象文件链接
- 函数调用中参数的顺序重要吗
- 为什么不;名字在地图上是按顺序排列的吗
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 数到第n个楼梯的路(顺序无关紧要)
- 在类定义之后定义一个私有方法
- 优先顺序:智能指针和类析构函数
- 在循环C++中指定字符串之后,不会打印该字符串
- 在循环中按顺序遍历成员变量
- 独立读取-修改-写入顺序
- C++宏忽略之后的内容
- QML按钮点击功能执行顺序
- 要与"if constexpr"一起使用的编译时消息(在预处理器之后)
- C++中数据类型修饰符的顺序
- 当比特(而不是字节)的顺序至关重要时的持久性
- C++从其他 constexpr 创建 lambda 不能按顺序执行 Constexpr
- C++ 中的优先级队列在 pop() 之后顺序不正确
- 松弛的内存顺序效果是否可以扩展到执行线程的生命周期之后?
- 在类型演绎之后,函数模板中的替换顺序是否有任何保证