优先队列的用法

转自:LINK_优先队列

优先队列用法:

在优先队列中,优先级高的元素先出队列。
标准库默认使用元素类型的<操作符来确定它们之间的优先级关系。
优先队列的第一种用法,也是最常用的用法:

priority_queue<int> qi;

通过<操作符可知在整数中元素大的优先级高。
故示例1中输出结果为:9 6 5 3 2

第二种方法:
在示例1中,如果我们要把元素从小到大输出怎么办呢?
这时我们可以传入一个比较函数,使用functional.h函数对象作为比较函数。

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

其中
第二个参数为容器类型。
第二个参数为比较函数。
故示例2中输出结果为:2 3 5 6 9

第三种方法:
自定义优先级。

1 struct node
2 {
3     friend bool operator< (node n1, node n2)
4     {
5         return n1.priority < n2.priority;
6     }
7     int priority;
8     int value;
9 };

在该结构中,value为值,priority为优先级。
通过自定义operator<操作符来比较元素中的优先级。
在示例3中输出结果为:
优先级  值
9          5
8          2
6          1
2          3
1          4
但如果结构定义如下:

1 struct node
2 {
3     friend bool operator> (node n1, node n2)
4     {
5         return n1.priority > n2.priority;
6     }
7     int priority;
8     int value;
9 };

则会编译不过(G++编译器)
因为标准库默认使用元素类型的<操作符来确定它们之间的优先级关系。
而且自定义类型的<操作符与>操作符并无直接联系,故会编译不过。

当然若要按优先级从小到大输出且要用第三中方法的话则按下面定义:

1 struct node
2 {
3     friend bool operator< (node n1, node n2)
4     {
5         return n1.priority > n2.priority;
6     }
7     int priority;
8     int value;
9 };

输出为:

优先级  值
1          4

2          3

6          1

8          2

9          5

下面附上上面所谈到的各种方法的代码【出点三种方法的最后面从小到大排的示例~】:

 1 //代码清单
 2 
 3 #include<iostream>
 4 #include<functional>
 5 #include<queue>
 6 using namespace std;
 7 struct node
 8 {
 9     friend bool operator< (node n1, node n2)
10     {
11         return n1.priority < n2.priority;
12     }
13     int priority;
14     int value;
15 };
16 int main()
17 {
18     const int len = 5;
19     int i;
20     int a[len] = {3,5,9,6,2};
21     //示例1
22     priority_queue<int> qi;
23     for(i = 0; i < len; i++)
24         qi.push(a[i]);
25     for(i = 0; i < len; i++)
26     {
27         cout<<qi.top()<<" ";
28         qi.pop();
29     }
30     cout<<endl;
31     //示例2
32     priority_queue<int, vector<int>, greater<int> >qi2;
33     for(i = 0; i < len; i++)
34         qi2.push(a[i]);
35     for(i = 0; i < len; i++)
36     {
37         cout<<qi2.top()<<" ";
38         qi2.pop();
39     }
40     cout<<endl;
41     //示例3
42     priority_queue<node> qn;
43     node b[len];
44     b[0].priority = 6; b[0].value = 1; 
45     b[1].priority = 9; b[1].value = 5; 
46     b[2].priority = 2; b[2].value = 3; 
47     b[3].priority = 8; b[3].value = 2; 
48     b[4].priority = 1; b[4].value = 4; 
49 
50     for(i = 0; i < len; i++)
51         qn.push(b[i]);
52     cout<<"优先级"<<'\t'<<""<<endl;
53     for(i = 0; i < len; i++)
54     {
55         cout<<qn.top().priority<<'\t'<<qn.top().value<<endl;
56         qn.pop();
57     }
58     return 0;
59 }
posted @ 2013-08-25 21:41  Teilwall  阅读(424)  评论(0编辑  收藏  举报