admin管理员组文章数量:1624343
priority_queue本质是一个堆。
1、priority_queue说明
头文件:#include<queue>
函数原型:
priority_queue<Type, Container, Functional>
其中Type 为数据类型,Container为保存数据的容器,Functional 为元素比较方式。Container必须是用数组实现的容器,比如vector,deque等等,但不能用 list。STL里面默认用的是vector。
2、priority_queue中元素的比较
用法一:
优先队列的第一种用法,也是最常用的用法:
priority_queue<int> q;
比较方式默认用operator<操作符操作,所以如果把后面2个参数缺省的话,优先队列就是大顶堆(降序),队头元素最大。
以下代码返回一个降序输出:
#include <iostream>
#include <queue>
using namespace std;
int main()
{
priority_queue<int> q;
int a[] = {10,8,1,6,3,5,2,9,4,7};
int len = sizeof(a) / sizeof(a[0]);
for (int i = 0; i< len; i++)
q.push(a[i]);
while (!q.empty())
{
cout << q.top() << " ";
q.pop();
}
cout << endl;
return 0;
}
用法二:
如果要用到小顶堆,则一般要把模板的三个参数都带进去。STL里面定义了一个仿函数 greater<>,对于基本类型可以用这个仿函数声明小顶堆。需要添加头文件#include<functional>
#include <iostream>
#include <queue>
#include <functional> // std::greater
using namespace std;
int main()
{
priority_queue<int, vector<int>, greater<int> > q;
int a[] = {10,8,1,6,3,5,2,9,4,7};
int len = sizeof(a) / sizeof(a[0]);
for (int i = 0; i< len; i++)
q.push(a[i]);
while (!q.empty())
{
cout << q.top() << " ";
q.pop();
}
cout << endl;
return 0;
}
用法三:
自定义优先级。
#include<iostream>
#include<queue>
using namespace std;
struct node
{
friend bool operator< (node n1, node n2)
{
return n1.priority < n2.priority;
}
int priority;
int value;
};
int main()
{ priority_queue<node> q;
const int len = 5;
node b[len];
b[0].priority = 6; b[0].value = 1;
b[1].priority = 9; b[1].value = 5;
b[2].priority = 2; b[2].value = 3;
b[3].priority = 8; b[3].value = 2;
b[4].priority = 1; b[4].value = 4;
for (int i = 0; i < len; i++)
q.push(b[i]);
cout << "优先级" << '\t' << "值" << endl;
for (int i = 0; i < len; i++)
{
cout << q.top().priority << '\t' << q.top().value << endl;
q.pop();
}
return 0;
}
本文标签: priorityqueue
版权声明:本文标题:priority_queue的用法 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/xitong/1728897042a1178543.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论