定义
队列的一种特殊形式,我们可以自定义该队列中数据的优先级,并且没有front()
和back()
函数,只使用top()
访问头文件。(有点像栈?)
基本操作
- top
- empty 队列是否为空
- size
- push
- emplace 构造一个元素插入队列
- pop
原型定义
priority_queue<Type, Container, Functional>
Type 是数据类型,Container 是容器类型(Container 必须是用数组实现的容器,比如 vector, deque 等,不能使用 list,默认 vector),Function 是比较方法。
使用例
1 2 3 4 5 6 7 8 9
| //greater和less是std实现的两个仿函数 //就是使一个类的使用看上去像一个函数,其实现就是类中实现一个operator() //这个类就有了类似函数的行为,就是一个仿函数类了
//降序队列(默认大根堆) priority_queue <int,vector<int>,less<int> >q; //升序队列(小根堆) priority_queue <int,vector<int>,greater<int> > q;
|
头文件使用queue
即可
重写仿函数
1 2 3 4 5 6 7
| class cmp{ public: bool operator () (fruit f1,fruit f2){ return f1.price>f2.price; //相当于小根堆,就是改变<的含义,那就相当于改变优先队列默认模式那就是小根堆 return f1.price<f2.price; //相当于默认大根堆,就是没改变<的含义,那就相当于是优先队列默认模式那就是大根堆 } };
|