正在创建STL最小堆优先级队列

Creating a STL min heap priority queue?

本文关键字:优先级 队列 创建 STL      更新时间:2023-10-16

我的任务是实现一个最小堆优先级队列,用m_time成员变量对每个队列对象进行排序。我的问题是,我无法管理队列以先排序最小而不是最大。

我在.h文件中有一个名为Event的结构,它包括三个变量:

struct Event
{ 
 Event(int time=-1, int grind=-1, bool val=false) 
 { m_time=time;m_grindNr=grind; m_value=val;}
    int  m_time;
    int  m_grindNr;
    bool m_value;
};

下面的代码是.cpp文件中的内容:

struct compare
{
    bool operator()(const Event& a, const Event& b)
    {
        return a.m_time < b.m_time;
    }
};

void main()
{
    priority_queue <Event,vector<Event>, compare> Que;
    Event firstEvent;
    firstEvent.m_time = 2;
    firstEvent.m_grindNr = 0;
    firstEvent.m_value = 0;
    Que.push(firstEvent);
    Event secondEvent;
    secondEvent.m_time = 5;
    secondEvent.m_grindNr = 0;
    secondEvent.m_value = 0;
    Que.push(secondEvent);
    Event tempEvent = Que.top(); //Takes the top value
    Que.pop();
    cout << tempEvent.m_time << " "; //Should print number 2, but prints 5
    tempEvent = Que.top(); //Takes the top value
    Que.pop();
    cout << tempEvent.m_time << endl; //Should print number 5, but prints 2
}

我还尝试在优先级队列参数中使用std::less,但结果相同。

我希望你能理解我的问题,提前谢谢。

您必须使用greater,因为priority_queue首先获取最大

因此,将您的比较更改为

return b.m_time < a.m_time;