您的位置:首页 > 编程语言 > C语言/C++

C++ 之 优先队列 priority_queue

2016-04-20 15:09 585 查看
解释:严格上而言不算队列,因为队列遵循先进先出;优先队列则是按照规则进行出队

使用:

(一)直接定义:

priority_queue<int>q1;
定义一个优先队列q1,队列则按照降序(从大到小出队);

样例一:

int a[5]={3,1,2,4,5};
priority_queue<int>q1;
for(int i = 0 ; i<5;i++)
q1.push(a[i]);
for(int i = 0 ; i < 5;i++)
{
printf("%d ",q1.top());
q1.pop();
}
printf("\n");</span></strong>


输出:5 4 3 2 1 ;

(二)使用特定函数排序;

priority_queue<int,vector<int>,greater<int> >q2;//*这里的>>一定要分开!
greater是从小到大的排序函数;

第二个参数:容器函数;

第三个参数:比较函数;

样例二:

int a[5]={3,1,2,4,5};
priority_queue<int,vector<int>,greater<int> >q2;
for(int i = 0 ; i < 5;i++)
q2.push(a[i]);
for(int i = 0 ; i <5;i++)
{
printf("%d ",q2.top());
q2.pop();
}
printf("\n");
输出:1 2 3 4 5 ;



(三)自定义优先级;(和sort类似)

比较成员函数:(结构体)

struct node
{
friend bool operator< (node n1, node n2)
{
return n1.p < n2.p;
}
int p;
int val;
}b[5];  //*这里面没有 > 符号, 只支持 <; </span></strong>
定义方式:

priority_queue<node>q3;
样例三:

#include<iostream>
#include<functional>
#include<queue>
using namespace std;
struct node
{
friend bool operator< (node n1, node n2)
{
return n1.priority < n2.priority;
}
int priority;
int value;
};
int main()
{
const int len = 5;
int i;
int a[len] = {3,5,9,6,2};
//示例3
priority_queue<node> qn;
node b[len];
b[0].priority = 6; b[0].value = 1;
b[1].priority = 9; b[1].value = 5;
b[2].priority = 2; b[2].value = 3;
b[3].priority = 8; b[3].value = 2;
b[4].priority = 1; b[4].value = 4;

for(i = 0; i < len; i++)
qn.push(b[i]);
cout<<"优先级"<<'\t'<<"值"<<endl;
for(i = 0; i < len; i++)
{
cout<<qn.top().priority<<'\t'<<qn.top().value<<endl;
qn.pop();
}
return 0;
}

输出:

优先级值

9 5

8 2

6 1

2 3

1 4
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: