优先队列小结

 

不像栈和队列,虽然STL有较好实现但是我们自己也可以很方便的实现,优先队列自己实现起来就比较复杂,比较浪费时间(而且自己目前也不会233)而优先队列因为其较好的特性经常被使用,因此对它的熟练掌握是做题的基础。

头文件#include< queue >
定义方法:

  • 普通方法
    priority_queue< int ,vector< int> ,greater< int> > q小的优先级比较高,大的后出队
    pritority_queue<int ,vector< int>,less< int > >q大的优先级比较高先出队,小的后出队
    为方便记忆,最好理解成比较函数是为了确定队尾元素的优先级
    需要注意比较函数右边> >中间应该用空格隔开,否则会被看成>>出错
    默认情况下,即priority_queue q;是小的先出队大的后出队
  • 自定义优先级
struct cmp
{
	bool operator()(int x,int y)
	{
		return x>y;//x小的优先级高 
	}
};
protority_queue<int,vector<int>,cmp>;
  • 结构体定义
struct node
{
	int x,y;
	friend bool operator < (node a,int b)
	{
		return a.x>b.x;	//x小的优先级高 
	}
};
priority_queue<node>q;
  • 其他常用的操作
    empty() //如果队列为空返回为真
    pop() //删除队顶元素
    push() //加入一个元素
    size() //返回队列中元素的个数
    top() //返回优先队列队顶元素

 

posted on 2019-03-28 23:53  qgmzbry  阅读(115)  评论(0编辑  收藏  举报

导航