priority_queue添加元素时,默认情况下,会把该元素按大小顺序插入到元素中。
但吊诡的是,如果连续插入的几个元素值相同,则他们在队列中的排列顺序完全没有规律。
实验结果如下:
struct node
{
int x,y;
node(int x1=0,int y1=0):x(x1),y(y1){}
bool friend operator<(node a,node b)
{
return a.x<=b.x;
}
};
int main()
{
priority_queue<node> pq;
node a;
pq.push(node(1,2));
pq.push(node(1,3));
pq.push(node(1,4));
pq.push(node(1,5));
pq.push(node(1,1));
while(!pq.empty())
{
node v=pq.top();
pq.pop();
printf("x: %d y: %d\n",v.x,v.y);
}
}运行结果:
可见优先队列完全没有了原先队列 先进先出的特性。
比较函数传递:
第一种,直接使用默认的。
它的模板声明带有三个参数,priority_queue<Type, Container, Functional>
Type 为数据类型, Container 为保存数据的容器,Functional 为元素比较方式。
Container 必须是用数组实现的容器,比如 vector, deque 但不能用 list.
STL里面默认用的是 vector. 比较方式默认用 operator< , 所以如果你把后面俩个
参数缺省的话,优先队列就是大顶堆,队头元素最大。
看例子
priority_queue<int> qi;
int a[len] = {3,5,9,6,2};
priority_queue<int> qi;
for(i = 0; i < len; i++)
qi.push(a[i]);
for(i = 0; i < len; i++)
{
cout<<qi.top()<<" ";
qi.pop();
}
通过<操作符可知在整数中元素大的优先级高。
故例子中输出结果为:9 6 5 3 2
第二种:
第二种方法:
在示例1中,如果我们要把元素从小到大输出怎么办呢?
这时我们可以传入一个比较函数,使用functional.h函数对象作为比较函数。
如果要用到小顶堆,则一般要把模板的三个参数都带进去。
STL里面定义了一个仿函数 greater<>,对于基本类型可以用这个仿函数声明小顶堆
priority_queue<int, vector<int>, greater<int> >qi2;
对于自定义类型,则必须自己重载 operator< 或者自己写仿函数
#include <iostream>
#include <queue>
using namespace std;
struct Node{
int x, y;
Node( int a= 0, int b= 0 ):
x(a), y(b) {}
};
bool operator<( Node a, Node b ){
if( a.x== b.x ) return a.y> b.y;
return a.x> b.x;
}
int main(){
priority_queue<Node> q;
for( int i= 0; i< 10; ++i )
q.push( Node( rand(), rand() ) );
while( !q.empty() ){
cout << q.top().x << ' ' << q.top().y << endl;
q.pop();
}
getchar();
return 0;
}
或者这样定义也是能达到效果的:
struct Node{
int x, y;
Node( int a= 0, int b= 0 ):
x(a), y(b) {}
friend operator<( Node a, Node b ){
if( a.x== b.x ) return a.y> b.y;
return a.x> b.x;
}
};
自定义类型重载 operator< 后,声明对象时就可以只带一个模板参数。
但此时不能像基本类型这样声明
priority_queue<Node, vector<Node>, greater<Node> >;
原因是 greater<Node> 没有定义,如果想用这种方法定义
则可以按如下方式
例子:
#include <iostream>
#include <queue>
using namespace std;
struct Node{
int x, y;
Node( int a= 0, int b= 0 ):
x(a), y(b) {}
};
struct cmp{
bool operator() ( Node a, Node b ){
if( a.x== b.x ) return a.y> b.y;
return a.x> b.x; }
};
int main(){
priority_queue<Node, vector<Node>, cmp> q;
for( int i= 0; i< 10; ++i )
q.push( Node( rand(), rand() ) );
while( !q.empty() ){
cout << q.top().x << ' ' << q.top().y << endl;
q.pop();
}
getchar();
return 0;
}
还有一点要注意的是priority_queue中的三个参数,后两个可以省去,因为有默认参数,不过如果,有第三个参数的话,必定要写第二个参数。
本文深入探讨了优先队列(priority_queue)的使用方法,包括默认的大顶堆行为、如何自定义比较函数实现小顶堆,以及如何处理自定义类型的元素。通过具体的代码示例展示了不同场景下的应用。
1423

被折叠的 条评论
为什么被折叠?



