C++STL容器

众所周知,C++STL中优先队列priority_queue默认是大根堆。

DIY一个优先队列有很多方法,下面记录一种方法:自定义容器参数之比较结构体。

一个优先队列的定义如下:(复制 from stl_queue.h)


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

即,有三个参数:类型、序列、比较,序列的默认值是vector,比较的默认值是less。

如果我们可以自定义比较结构体,自然就可以实现不同操作。

那么问题来了,这种比较结构体怎么写呢?

一番查找资料之后,我了解到,它需要在结构体内以bool类型重载"()"运算符。

struct cmp_small{
    bool operator ()(const int &a,const int &b){
        return a>b;
        
    }
    
};
    priority_queue<int,vector<int>,cmp_small >srh;

这样我们就定义了一个小根堆。

原文地址:https://www.cnblogs.com/Hansue/p/11236440.html