优先级队列

 

priority_queue<Type, Container, Functional>

其中Type为数据类型,Container为保存数据的容器,Functional为元素比较方式。Container必须是用数组实现的容器,比如 vector, deque. STL里面默认用的是vector. 比较方式默认用operator< , 所以如果把后面两个参数缺省的话,优先队列就是大顶堆,队头元素最大。
优先队列的时间复杂度为O(logn),n为队列中元素的个数,其存取都需要时间。

//升序队列,小顶堆
priority_queue <int,vector<int>,greater<int> > q;
//降序队列,大顶堆
priority_queue <int,vector<int>,less<int> >q;

 

std::priority_queue<TAStarNode, std::vector<TAStarNode>, compOpen> _openList;

struct compOpen //重写仿函数
{
  bool operator() (TAStarNode a, TAStarNode b)
  {
    if (a._f == b._f) return a._g < b._g;
    return a._f > b._f;
  }
};

 

 


struct stone{//这是一种自定义设置优先队列优先级的方法,重载默认的 < 符号
int p;
int d;
friend bool operator< (stone a,stone b){
if(a.p==b.p)
return a.d>b.d;/*注意这里的比较,这是写的数据越小优先级越高,即先取出数值小的元素其实也可以这么理解,队列我们是可以用数组来存储的,比较sort函数里我们写的cmp ,return a>b时 是按降序来排列的,eg :6 5 4 3 2 1,因为队列又是满足先进先出的原则,所以我们首先取出的是1,也就是数值最小的那个*/
return a.p>b.p;
}

 

posted @ 2022-03-21 18:39  高ws  阅读(117)  评论(0编辑  收藏  举报