STL总结之priority_queue

介绍

priority_queue 是容器适配器,它提供程序员堆数据结构的功能。
priority_queue 底层容器有两种可选—— vector、deque,默认使用 vector。
priority_queue 定义于头文件 <queue> 中 ,其声明如下:

template<
    class T,
    class Container = std::vector<T>,
    class Compare = std::less<typename Container::value_type>
> class priority_queue;

priority_queue 容器需要指定优先级,有两种方式可指定:

  • 以 类型参数 定义,如 priority_queue<T,vector<T>,greater<T> >。如果 T 非基本数据类型,则需实现重载运算符 < 。
    strcut T {
    	…… // 各种参数
    	// 该函数声明必须这样写
    	friend bool operator <(const T& a,const T& b)
    	{
    		// check(a,b)为 a < b 成立条件
    		return check(a,b) ? true : false;
    	}
     };
    
  • 以 构造函数参数 定义,在构造函数中传入排序函数。
    bool cmp(const T& a,const T& b)
    {
     	// check(a,b)为 a < b 成立条件
     	return check(a,b) ? true : false;
    }
    

成员函数

  • 构造函数
    • priority_queue<T,Container> pq(cmp)
      Container 可取值:vector<T>deque<T>
      创建一个空的 priority_queue 容器,优先级根据 cmp 函数定义。
      cmp 函数可为空,默认升序。
      bool cmp(const int& a,const int& b)
      {
         return check(a,b) ? true : false;
      }
      priority_queue<int,vector<int>> pq(cmp);
      
    • priority_queue<T,Container> pq(pq1)
      创建一个 pq1 的同型拷贝 (所有元素都被复制)。
      priority_queue<int,vector<int>> pq1;
      priority_queue<int,vector<int>> pq(pq1);
      
  • empty()
    判断 priority_queue 容器是否为空。
  • size()
    返回 priority_queue 容器中元素个数。
  • top()
    访问队首元素。
  • push(num)
    priority_queue 容器中插入元素 num,并对容器排序。
  • pop()
    删除队首元素,并对容器排序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值