码迷,mamicode.com
首页 > 其他好文 > 详细

STL中优先队列的使用 转

时间:2014-11-02 22:28:01      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:blog   http   io   ar   os   使用   for   sp   strong   

队列的特点是先进先出。通常都把队列比喻成排队买东西,大家都很守秩序,先排队的人就先买东西。但是优先队列有所不同,它不遵循先进先出的规则,而是根据队列中元素的优先权,优先权最大的先被取出。通常把优先队列比喻成现实生活中的打印。一个打印店里有很多打印机,每台机器的性能不一样,有的打印机打印很快,有的打印机打印速度很慢。当这些打印机陆陆续续打印完自己的任务时进入排队等候状态。如果我这个时候要打印一份文件,我选的不是第一个排队的打印机,而是性能最好,打印最快的打印机。

重点:优先级队列,是要看优先级的,谁的优先级更高,谁就先得到权限。不分排队的顺序!

基本操作:

empty() 如果队列为空返回真

pop() 删除对顶元素

push() 加入一个元素

size() 返回优先队列中拥有的元素个数

top() 返回优先队列对顶元素

在默认的优先队列中,优先级高的先出队。在默认的int型中先出队的为较大的数。

使用方法:

头文件:

#include <queue>

声明方式:

1、普通方法:

priority_queue<int>q;
//通过操作,按照元素从大到小的顺序出队

2、自定义优先级:

struct cmp
{
operator bool ()(int x, int y)
{
return x > y; // x小的优先级高
//也可以写成其他方式,如: return p[x] > p[y];表示p[i]小的优先级高
}
};
priority_queue<int, vector<int>, cmp>q;//定义方法
//其中,第二个参数为容器类型。第三个参数为比较函数。
 

3、结构体声明方式:

struct node
{
int x, y;
friend bool operator < (node a, node b)
{
return a.x > b.x; //结构体中,x小的优先级高
}
};
priority_queue<node>q;//定义方法
//在该结构中,y为值, x为优先级。
//通过自定义operator<操作符来比较元素中的优先级。
//在重载”<”时,最好不要重载”>”,可能会发生编译错误
示例:
[cpp] view plaincopybubuko.com,布布扣bubuko.com,布布扣
 
  1. #include "iostream"  
  2. #include "vector"  
  3. #include "queue"  
  4. using namespace std;  
  5. int c[100];  
  6. struct cmp1  
  7. {  
  8.      bool operator ()(int x, int y)  
  9.     {  
  10.         return x > y;//小的优先级高  
  11.     }  
  12. };  
  13.   
  14. struct cmp2  
  15. {  
  16.     bool operator ()(const int x, const int y)  
  17.     {  
  18.         return c[x] > c[y];   
  19.        // c[x]小的优先级高,由于可以在对外改变队内的值,  
  20.         //所以使用此方法达不到真正的优先。建议用结构体类型。  
  21.     }  
  22. };  
  23.   
  24. struct node  
  25. {  
  26.     int x, y;  
  27.     friend bool operator < (node a, node b)  
  28.     {  
  29.         return a.x > b.x;//结构体中,x小的优先级高  
  30.     }  
  31. };  
  32.   
  33. priority_queue<int>q1;  
  34. priority_queue<int, vector<int>, cmp1>q2;  
  35. priority_queue<int, vector<int>, cmp2>q3;  
  36. priority_queue<node>q4;  
  37.   
  38. queue<int>qq1;  
  39. queue<node>qq2;  
  40.   
  41. int main()  
  42. {  
  43.     int i, j, k, m, n;  
  44.     int x, y;  
  45.     node a;  
  46.     while (cin >> n)  
  47.     {  
  48.         for (i = 0; i < n; i++)  
  49.         {  
  50.             cin >> a.y >> a.x;  
  51.             q4.push(a);  
  52.         }  
  53.         cout << endl;  
  54.         while (!q4.empty())  
  55.         {  
  56.             cout << q4.top().y << " " << q4.top().x << endl;  
  57.             q4.pop();  
  58.         }  
  59.     //    cout << endl;  
  60.     }  
  61.     return 0;  
  62. }  

STL中优先队列的使用 转

标签:blog   http   io   ar   os   使用   for   sp   strong   

原文地址:http://www.cnblogs.com/tyx0604/p/4070034.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!