简体   繁体   English

创建 STL 最小堆优先级队列?

[英]Creating a STL min heap priority queue?

My task is to implement a min heap priority queue sorting each queue object with the m_time member variable.我的任务是实现一个最小堆优先级队列,使用 m_time 成员变量对每个队列对象进行排序。 My problem is that I can't manage the queue to sort smallest first instead of largest.我的问题是我无法管理队列以先排序最小而不是最大。

I have a struct in the .h file called Event that includes three variables:我在 .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;
};

The code below is what's inside the .cpp file:下面的代码是 .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
}

I have also tried using the std::less in the priority queue parameter but its the same result.我也尝试在优先级队列参数中使用 std::less ,但结果相同。

I hope you understand my question, thanks in advance.我希望你能理解我的问题,在此先感谢。

You have to use greater , as priority_queue take largest first.您必须使用greater ,因为 priority_queue 首先取最大

So change your compare to所以改变你的比较

return b.m_time < a.m_time;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM