C++ 优先队列的使用

首先看下优先队列的STL源码:

class priority_queue
{
     protected:
         _Sequence  c;                  ///容器
        _Compare   comp;          ///比较准则
     public:
     bool empty() const
     { return c.empty(); }
     size_type size() const
     { return c.size(); }
     const_reference top() const
     {
         __glibcxx_requires_nonempty();
         return c.front();
     }
     void push(const value_type& __x)
     {
         try
         {
          c.push_back(__x);
          std::push_heap(c.begin(), c.end(), comp);
        }
        catch(...)
        {
           c.clear();
           __throw_exception_again;
         }
     }
     void pop()
     {
         __glibcxx_requires_nonempty();
         try
         {
           std::pop_heap(c.begin(), c.end(), comp);
           c.pop_back();
         }
         catch(...)
         {
           c.clear();
           __throw_exception_again;
         }
     }

}

用法:

C++头文件 #include <queue>

template<typename _Tp,
             typename _Sequence = vector<_Tp>,
             typename _Compare  = less<typename _Sequence::value_type> >

第一个参数 _Tp: 指定存储的类型名称;

第二个参数 _Sequence: 指定存储的数据结构,该结果必须支持随机存取迭代器;

第三个参数 _Compare : 比较函数,对于自定义类型有两种方法实现大小顶堆,第一个是重载操作符,第二个是写一个结构实现比较。

各个数据类型算法讲解如下:

1.  对于一般的基本数据类型,比如 int,double等。

1).    默认是大顶堆,测试代码如下

int main()
{
    priority_queue<int,vector<int>, less<int> > max;
    for(int i=0;i<10;i++){
        max.push(rand()%20);
    }
    while(!max.empty()){
        cout<<max.top()<<" ";
        max.pop();
    }
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值