std::priority_queue:在优先队列中,优先级高的元素先出队列,并非按照先进先出的要求,类似一个堆(heap)。
其模板声明带有三个参数,priority_queue<Type, Container, Functional>, 其中
- Type为数据类型,Container为保存数据的容器,Functional为元素比较方式。
- Container必须是用数组实现的容器,比如 vector, deque. STL里面默认用的是vector.
- 比较方式默认用operator< , 所以如果把后面两个参数缺省的话,优先队列就是大顶堆,队头元素最大。
- 使用greater<>后,数据从大到小排列,top()返回的就是最小值而不是最大值!(变为小顶堆)
- 如果使用了第三个参数,那第二个参数不能省,用作保存数据的容器
priority_queue<int,vector<int> , greater<>> pq;//这是对的
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> aa = {1, 2, 3, 4, 5, 6, 7, 8, 9};
priority_queue<int> que;
for (int i = 0; i < aa.size(); i++)
{
que.push(aa[i]);
}
sort(aa.begin(), aa.end());
for (int i = 0; i < aa.size(); i++)
{
cout << aa[i] << endl;
}
cout << que.top() << endl; //9
return 0;
}
Comments NOTHING