优先队列是用堆实现的
<pre name="code" class="cpp">
操作有:
<span style="white-space:pre"> </span>empty();
<span style="white-space:pre"> </span>top();
<span style="white-space:pre"> </span>pop();
<span style="white-space:pre"> </span>push();
<span style="white-space:pre"> </span>size();
因为是用堆实现的缘故,所以没有查找的函数。(堆不是二叉查找树,找最小或最大容易,想查找,就要遍历整个堆。反正查找效率很低,要查找请用set或map)
<pre style="margin-top: 0px; margin-bottom: 0px; background-color: rgb(239, 239, 255);"><code><dfn style="font-style: normal; color: rgb(80, 0, 112);">#include <iostream> </dfn><cite style="font-style: normal; color: rgb(0, 112, 0);">// std::cout</cite>
<dfn style="font-style: normal; color: rgb(80, 0, 112);">#include <queue> </dfn><cite style="font-style: normal; color: rgb(0, 112, 0);">// std::priority_queue</cite>
<dfn style="font-style: normal; color: rgb(80, 0, 112);">#include <vector> </dfn><cite style="font-style: normal; color: rgb(0, 112, 0);">// std::vector</cite>
<dfn style="font-style: normal; color: rgb(80, 0, 112);">#include <functional> </dfn><cite style="font-style: normal; color: rgb(0, 112, 0);">// std::greater</cite></code>
//使用优先队列会是使用到的头文件
<span style="white-space:pre"> </span>priority_queue<int> pr;//这是最普通的定义优先队列的方法,默认最大值优先,适用于已定义的数据类型
<span style="white-space:pre"> </span>//第一个参数int代表数据类型
<span style="white-space:pre"> </span>priority_queue<int,vector<int>,less<int> > pr;<span style="white-space:pre"> </span>//最小值优先
<span style="white-space:pre"> </span>priority_queue<int,vector<int>,greater<int> > pr;<span style="white-space:pre"> </span>//最大值优先
<span style="white-space:pre"> </span>//把参数补充完整,就是这种定义方式
<span style="white-space:pre"> </span>//第一个参数是数据类型,第二个参数是容器适配器,第三个是比较规则是个模版类型less,greater是自带的最大最小值,只能比较已有数据类型。
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>//如果定义优先队列的元素是自定义类型的,比如
<span style="white-space:pre"> </span>class A {
<span style="white-space:pre"> </span>public:
<span style="white-space:pre"> </span>int val;
<span style="white-space:pre"> </span>};
<span style="white-space:pre"> </span>//上面两种定义肯定是无法满足的,因为无法比较class A这个类型,不知道大小规则,也就无法建堆了;
<span style="white-space:pre"> </span>//所以必须要自定义一下规则,重载一下()
<span style="white-space:pre"> </span>class A{
<span style="white-space:pre"> </span>public:
<span style="white-space:pre"> </span>bool operator < (const A &a,const A &b)const{
<span style="white-space:pre"> </span>return a.val < b.val; //从小到大,因为值
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>int val;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>//你说为啥重载()?肯定是比较的时候调用了();
<span style="white-space:pre"> </span>//写好重载之后
<span style="white-space:pre"> </span>priority_queue<A,vector<A>,A>
<span style="white-space:pre"> </span>//其实第三个参数A是要填方法类的。。。。不过无妨
<span style="white-space:pre"> </span>//也可以重载 <
<span style="white-space:pre"> </span>priority_queue<A> qr;
<span style="white-space:pre"> </span>
参考:http://www.cnblogs.com/summerRQ/articles/2470130.html