STL之priority_queue

来源:互联网 发布:java报表程序 编辑:程序博客网 时间:2024/05/21 06:26

priority_queue是优先级队列,主要应用于需要自动排序的情况,比如录入成绩。

一、priority_queue的基本操作

#include<iostream>#include<queue>#include<functional>using namespace std;void func1() {    priority_queue<int> pq1;    priority_queue<int, vector<int>, less<int>> pq2;    priority_queue<int, vector<int>, greater<int> > pq3;    pq1.push(33);    pq1.push(11);    pq1.push(55);    pq1.push(22);    cout << " 最大值优先队列队头为: "<< pq1.top() << endl;    cout << " 最大值优先队列大小为: " << pq1.size() << endl;    while (pq1.size() > 0) {        cout << pq1.top() << " ";        pq1.pop();    }    cout << endl;    pq2.push(33);    pq2.push(11);    pq2.push(55);    pq2.push(22);    cout << " 最大值优先队列队头为: " << pq2.top() << endl;    cout << " 最大值优先队列大小为: " << pq2.size() << endl;    while (pq2.size() > 0) {        cout << pq2.top() << " ";        pq2.pop();    }    cout << endl;    pq3.push(33);    pq3.push(11);    pq3.push(55);    pq3.push(22);    cout << " 最小值优先队列队头为: " << pq3.top() << endl;    cout << " 最小值优先队列大小为: " << pq3.size() << endl;    while (pq3.size() > 0) {        cout << pq3.top() << " ";        pq3.pop();    }    cout << endl;}int main(){    func1();    system("pause");    return 0;}

输出结果:

这里写图片描述

可以看到

priority_queue<int> pq1;

默认就是最大值优先,

priority_queue<int, vector<int>, less<int>> pq2;

这种形式也是最大值优先;

priority_queue<int, vector<int>, greater<int> > pq3;

这种形式是最小值优先。其中的less和greater需要头文件,是预先定义好的函数。

0 0
原创粉丝点击