Peng Lv

毋意,毋必,毋固,毋我。 言必行,行必果。

导航

C++STL priority_queue 学习

本文来源自网上摘抄,故学习记录于此。

 

包含priority_queue 的头文件是 <queue>

 

priority_queue类的主要成员:

priority_queue();    //默认构造函数,生成一个空的排序队列

priority_queue(const queue&);    //拷贝构造函数

priority_queue& operator=(const priority_queue &);    //赋值运算符重载

priority_queue 的私有成员:

value_type;   //priority_queue中存放的对象类型,它和priority_queue中的T类型相同

priority_queue(const Compare& comp);    //构造生成一个空的priority_queue对象,使用comp作为priority_queue的comparison

priority_queue(const value_type* first, const value_type* last);    //带有两个参数的构造 函数,使用默认的Comparison作为第三个参数

size_type;    //正整数类型,和Sequence::size_type类型一样。

bool empty() const;    //判断优先级队列是否为空,为空返回true,否则返回false

size_type size() const;    //返回优先级队列中的元素个数

const value_type& top() const();    //返回优先级队列中第一个元素的参考值。

void push(const value_type& x);    //把元素x插入到优先级队列的尾部,队列的长度加1

void pop();    //删除优先级队列的第一个值,前提是队列非空,删除后队列长度减1

 

priority_queue<Type, Container, Functional>

 如果我们把后面俩个参数缺省的话,优先队列就是大顶堆,队头元素最大。(这点由上面的程序可以看出)

Parameter

Description

Default

T

The type of object stored in the priority queue.

 

Sequence

The type of the underlying container used to implement the priority queue.

vector<T>

Compare

The comparison function used to determine whether one element is smaller than

another element. If Comparex,y) is true, then x is smaller than y. The element

returned by Q.top) is the largest element in the priority queue. That is, it has the

 property that, for every other element x in the priority queue, Compare(Q.top(), x) is false.

less<T>

 

自定义类型重载 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();
}
return EXIT_SUCCESS;
}

 

 

 

posted on 2010-04-05 14:47  Lvpengms  阅读(3866)  评论(0编辑  收藏  举报