您的位置:首页 > 编程语言 > C语言/C++

c++ priority_queue 优先队列

2017-09-07 15:24 141 查看
priority_queue

Syntax:

In their implementation in the C++ Standard Template Library, priority queues take three template parameters:1

2 template < class T, class Container = vector,

class Compare = less > class priority_queue;

Where the template parameters have the following meanings:

T: Type of the elements.

Container: Type of the underlying container object used to store and access the elements.

Compare: Comparison class: A class such that the expression comp(a,b), where comp is an object of this class and a and b are elements of the container, returns true if a is to be placed earlier than b in a strict weak ordering operation. This can either be a class implementing a function call operator or a pointer to a function. This defaults to less, which returns the same as applying the less-than operator .

The priority_queue object uses this expression when an element is inserted or removed from it (using push or pop, respectively) to grant that the element popped is always the greater in the priority queue.

T

容器所包含的元素的类型。

在类模板内部,使用其别名为 value_type 的成员类型。

Container

底层的用于存储元素的容器的类型。必须是用数组实现的容器,比如 vector, deque 但不能用 list.

Compare

一个二元谓词,以两个元素为参数返回一个 bool 值。

可以是函数指针(Function pointer)类型或函数对象(Function object)类型。STL里面默认用的是 vector. 比较方式默认用 operator< , 所以如果你把后面俩个参数缺省的话,优先队列就是大顶堆,队头元素最大。

如果要用到小顶堆,则一般要把模板的三个参数都带进去。

STL里面定义了一个仿函数 greater<>,对于基本类型可以用这个仿函数声明小顶堆

priority_queue<int,vector<int>, greater< int> > qi2;


自定义优先级 compare

首先看一下less模板类:

template <class T> struct less {
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;
};


在一个struct里面实现了()操作符,我们可以类比这个方式实现自己的比较函数。

小顶堆的比较函数如下:

struct bigger{
bool operator()(pair<int,int> &a,pair<int,int>&b)
{
return a.first > b.first;
}
};


大顶堆的比较函数如下:

struct smaller{
bool operator()(class &a,class &b)
{
return a.first < b.first;
}
};


priority_queue成员函数

top 访问顶部元素

empty 判断是否为空

size 返回有效元素个数

push 在容器顶部插入元素

pop 移除容器顶部的元素
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息