队列与优先队列(堆)priority_queue*(详细+体会+重载结构体)
C++ Queues(队列)
C++队列是一种容器适配器,它给予程序员一种先进先出(FIFO)的数据结构。
1.back() 返回一个引用,指向最后一个元素
2.empty() 如果队列空则返回真
3.front() 返回第一个元素
4.pop() 删除第一个元素
5.push() 在末尾加入一个元素
6.size() 返回队列中元素的个数
队列可以用线性表(list)或双向队列(deque)来实现(注意vector container 不能用来实现queue,因为vector 没有成员函数pop_front!):
queue<list> q1;
queue<deque> q2;
其成员函数有“判空(empty)” 、“尺寸(Size)” 、“首元(front)” 、“尾元(backt)” 、“加入队列(push)” 、“弹出队列(pop)”等操作。
例如:
int main()
{
queue<int> q;
q.push(4);
q.push(5);
printf("%d\n",q.front());
q.pop();
}
优先队列(堆)priority_queue*(最详细)
priority_queue 优先队列,其底层是用堆来实现的。在优先队列中,队首元素一定是当前队列中优先级最高的那一个。
在优先队列中,没有 front() 函数与 back() 函数,而只能通过 top() 函数来访问队首元素(也可称为堆顶元素),也就是优先级最高的元素。
(1) priority_queue d;
(2) priority_queue q;
//node是一个结构体
//结构体里重载了‘<’小于符号
//更为常见的是第二种方法
//体会优先队列
#include<cstdio>
#include<queue>
using namespace std;
priority_queue <int> q;
int main()
{
q.push(10);
q.push(8);
q.push(12);
q.push(14);
q.push(6);
while(!q.empty()){
printf("%d ",q.top());
q.pop();
}
}
优先队列-重载结构体写法
#include<cstdio>
#include<queue>
using namespace std;
struct node
{
int x,y;
bool operator < (const node & a) const//定义结构体优先级
{
return x<a.x;
}
}k;
priority_queue <node> q;
int main()
{
k.x=10,k.y=100; q.push(k);
k.x=12,k.y=60; q.push(k);
k.x=14,k.y=40; q.push(k);
k.x=6,k.y=80; q.push(k);
k.x=8,k.y=20; q.push(k);
while(!q.empty())
{
node m=q.top(); q.pop();
printf("(%d,%d) ",m.x,m.y);
}
return 0;
}
学如逆水行舟,不进则退