Sequence container in STL——priority_queue (priority queue)

Sequence container in STL——priority_queue (priority queue)

  priority_queue, namely "priority queue". Ordinary queue is a first-in, first-out data structure. Elements are appended at the end of the queue and deleted from the head of the queue. In the priority queue, elements are given priority. When accessing an element, the element with the highest priority is deleted first. Priority queues have the behavior characteristics of first in, largest out. It is usually implemented using heap data structure.
  Priority_queue is an important member of C++ STL, you need to include the header file when using it:

#include <queue>;

  Priority_queue is a kind of container adapter. The data in the container adapter is organized in different priority ways.

One, the initialization of priority_queue

There are the following ways, examples are as follows:

queue<int> a;
queue<int> b(a); //拷贝队列a给队列b

Two, important operations of priority_queue object

Listed as follows:

a.push(5); //将5压入队列的末端
a.pop(); //弹出队列的第一个元素(队顶元素),注意此函数并不返回任何值
a.top(); //返回优先队列中有最高优先级的元素
a.empty(); //判断a是否为空,空则返回ture,不空则返回false
a.size(); //返回队列的长度
a=b; //队列b赋值给队列a

Three, priority setting

There are several ways, listed as follows:

struct cmp1
{
    
    
    bool operator ()(const int &a,const int &b)
    {
    
    
       return a>b;//最小值优先
   	}
};
struct cmp2
{
    
    
	bool operator ()(const int &a,const int &b)
	{
    
    
	    return a<b;//最大值优先
	}
};
struct node1
{
    
    
	int u;
	bool operator < (const node1 &a) const
	{
    
    
		return u>a.u;//最小值优先
	}
};
struct node2
{
    
    
	int u;
	bool operator < (const node2 &a) const
	{
    
    
		return u<a.u;//最大值优先
	}
};
priority_queue<int>q1;//采用默认优先级构造队列,最大值优先
priority_queue<int,vector<int>,cmp1>q2;//最小值优先 
priority_queue<int,vector<int>,cmp2>q3;//最大值优先
priority_queue<int,vector<int>,greater<int> >q4;//最小值优先
//注意“>>”会被认为错误,因为这是右移运算符,所以这里用空格号隔开
priority_queue<int,vector<int>,less<int> >q5;//最大值优先
priority_queue<node1>q6;//最小值优先
priority_queue<node2>q7;//最大值优先

Guess you like

Origin blog.csdn.net/hyl1181/article/details/108567373