C++-STL Priority_queue(优先队列)学习

包含的头文件

#include <queue>

优先队列和队列差不多,都是在队尾插入(push)元素,从队头删除(pop)元素.但和队列有所不同的是,priorityQueue的top()先会查找队列中最大的数(队列默认最大数),pop()删除的top()找出来的数,即最大数(假设int类型),看起来就像队列先排了序一样。
priority_queue模板原型

template< class T ,class Sequence=vector<T> ,classCompare=less<typenameSequence::value_type> >class priority_queue;

优先队列的日常使用方法
<1>默认优先级:

#include <queue>
std::priority_queue<int> pq;//默认从大到小排

<2>传入比较结构体,自定义优先级。

#include <queue>
using namespace std;
struct cmp1
{
    
    
	bool operator()(int a, int b){
    
    
		return a>b;//最小值优先
	}
};

也可以使用functional.h中的greater< class T>类模板,其模板原型为

template <class T> struct greater {
    
    
  bool operator() (const T& x, const T& y) const {
    
    return x>y;}
  typedef T first_argument_type;
  typedef T second_argument_type;
  typedef bool result_type;
};

<3>自定义的数据结构,自定义优先级

#include <queue>
using namespace std;
struct node{
    
    
	int data;
	friend bool operator < (const node &a, const node &b){
    
    
		return a.data < b.data;
	}
};

————————————————————————————————
参考:
(1)https://blog.csdn.net/CerberuX/article/details/51762357
(2)http://www.cplusplus.com/reference/functional/greater/

猜你喜欢

转载自blog.csdn.net/qq_29757633/article/details/87530499