优先级队列 priority_queue

优先级队列分为:最小值优先队列和最大值优先队列。
此处的最大值、最小值是指队头的元素(增序、降序)。默认是创建最大值优先级队列。

优先队列是一种特殊的队列。 优先队列容器也是一种从一端进队另一端出队的队列。但是,与普通队列不同,队列中最大的元素总是位于队头位置,因此,优先队列并不符合先进先出的要求,出队时是将队列中的最大元素出队。

优先队列的基本操作包括判队列空empty(),返回队列中元素的个数size()、 出队列(不返回值)pop()、进队列(在队尾插人新元素)push() 和 返回优先队列队头元素的值(不删除该元素)top().

定义优先级的方法:

priority_queue<int>
默认定义int类型的最大值队列

priority_queue<int, vector<int>, less<int>>
定义int型的最大值优先队列

priority_queue<int, vector<int>, greater<int>>
定义int型的最小值队列

上面的定义中,less和greater相当于谓词,是预定义好的排序函数,我们称之为“仿函数”。

void main()
{
    //定义优先级队列(默认是最大值优先级队列)
    priority_queue<int> p1;
    
    //定义一个最大优先级队列
    //less是提前定义好的预定义函数 相当于谓词
    priority_queue<int, vector<int>, less<int>> p2;
    
    //定义一个最小值优先级队列v
    priority_queue<int, vector<int>, greater<int>> p3;
    
    //给默认的最大优先级队列入栈
    p1.push(33);
    p1.push(11);
    p1.push(55);
    p1.push(22);
    
    //打印最大优先级的对头元素
    cout<<"对头元素:"<< p1.top() <<endl;
    cout<<"队列的大小:"<< p1.size() <<endl;
    
    //给最小值优先级队列入栈
    p3.push(33);
    p3.push(11);
    p3.push(55);
    p3.push(22);
    
    //打印最小优先级队列的对头元素
    cout<<"对头元素:"<< p3.top() <<endl;
    cout<<"队列的大小:"<< p3.size() <<endl;
    
}

猜你喜欢

转载自blog.csdn.net/qq_42815188/article/details/88042636