@TOC
优先级队列 priority_queue 与 仿函数 greater / less
仿函数
定义及优点
定义:定义一个类,类里面重载函数运算符()
,将该类的对象作为函数的入参,那么在函数中同样能调用重载符()
里面的方法。
优点:相比于普通函数,仿函数的声明更为简单。
例如:用普通函数,仿函数写一个swap
函数,并将其以参数的形式,如下:
//普通函数
template<class T>
void _swap(T& a, T& b)
{
T c = a; a = b; b = c; }
//声明参数
void(*p)(int&, int&) = _swap;
再来看看仿函数写法:
```cpp
//仿函数
template<class T>
struct _swap
{
void operator()(T& a, T& b)
{
T c = a; a = b; b = c; }
};
//声明参数
_swap<int> p;
我们可以看到函数指针,在面向对象开发的过程中编写有点繁琐,所以C++的仿函数借此代替了函数指针。
有了上面理解的铺垫就可以,很轻松的理解下面两个仿函数了。
greater
template<class T>
class greater
{
public:
bool operator()(const T& a, const T& b)
{
return a > b;
}
};
less
template<class T>
class less
{
public:
bool operator()(const T& a, const T& b)
{
return a < b;
}
};
优先级队列
priority_queue
定义:优先级队列的本质其实是一个堆,插入数据时内部按照所给的仿函数为参考进行(堆)排序,确保第一个元素为最值,存在默认的缺省值,一般采用vector为适配器,Less为仿函数.
如下:
template <class T, class Container = vector<T>, class Compare &