您的位置:首页 > 其它

STL优先队列的使用

2014-09-06 21:17 405 查看
STL中有一个优先队列的容器可以使用。

【头文件】

queue 队列容器

vector 向量容器

【操作】

优先级队列支持的操作
q.empty() 如果队列为空,则返回true,否则返回false

q.size() 返回队列中元素的个数

q.pop() 删除队首元素,但不返回其值

q.top() 返回具有最高优先级的元素值,但不删除该元素

q.push(item) 在基于优先级的适当位置插入新元素

对于Pascal留下来的手打堆习惯来说,其实对我用处不大,不过好像STL里面的复杂度更低,代码长度也能少点,以后尽量用STL好了。

#include<iostream>
#include<cstdio>
#include<queue>

using namespace std;

struct cmp
{
bool operator()(int x,int y)
{
return x>y;
}
};

typedef struct nod
{
int x,y;
friend bool operator < (nod a,nod b)
{
return a.y>b.y;
}
} node;

int main()
{
priority_queue<int>simple;
priority_queue<int,vector<int>,cmp>define;
priority_queue<node>heap;

int a[10]={20,50,3202,20,503,12,56,62,50,80};

printf("Simple Test:\n");
for (int i=0;i<10;i++) simple.push(a[i]);
for (int i=1;i<=10;i++)
{
int temp=simple.top();
simple.pop();
printf("%d\n",temp);
}

printf("Define Test:\n");
for (int i=0;i<10;i++) define.push(a[i]);
for (int i=1;i<=10;i++)
{
int temp=define.top();
define.pop();
printf("%d\n",temp);
}

printf("Heap Test:\n");
node b[10]={{1,2},{2,100},{3,4},{4,50},{5,6},{6,7},{7,8},{8,9},{9,10},{10,11}};
for (int i=0;i<10;i++) heap.push(b[i]);
for (int i=1;i<=10;i++)
{
node temp=heap.top();
heap.pop();
printf("%d %d\n",temp.x,temp.y);
}

printf("%d",2<1);

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