容器适配器之优先级队列

和适配器栈、适配器队列类似,优先级队列也是一种容器适配器
template< class T,class Container=vector< T > >
class priority_queue;
优先级队列的基础容器必须是支持随机访问的顺序容器,因此它必须是vector或deque,默认为vector。

优先级队列也像栈和队列一样支持元素的压入和弹出,但是弹出的顺序和压入的顺序无关,而是与元素大小有关,每次弹出的总是容器中最“大”的一个元素。

**当容器的类型T是类或者结构体这样的复合数据类型时,“”<“”运算符必须有定义,优先级队列在默认情况下是按“”<“”运算符来决定元素大小的。**例子如下:


#include <iostream>
#include <ctime>
#include<iterator>
#include <queue>
using namespace std;

const int SPLIT_TIME_MIN = 500;	//细胞分裂最短时间
const int SPLIT_TIME_MAX = 2000;	//细胞分裂最长时间

class Cell;
priority_queue<Cell> CellQueue;//容器的类型是类,因此必须对“<”进行运算符重载

class Cell {	
private:
	static int count;	//细胞总数
	int id;		//当前细胞编号
	int time;	//细胞分裂时间
public:
	Cell(int birth) :id(count++) {	//birth为细胞诞生时间
		//初始化,确定细胞分裂时间
		time = birth + (rand() % (SPLIT_TIME_MAX - SPLIT_TIME_MIN)) + SPLIT_TIME_MIN;
	}
	int getId() const { return id; }	//得到细胞编号
	int getSplitTime() const { return time; }	
	bool operator< (const Cell& s) const { return time > s.time; }	//定义"<"

	//细胞分裂
	void split() const{
		Cell child1(time), child2(time);	//建立两个子细胞,细胞分裂时间作为下一个细胞出生时间
		cout << time << "s: Cell #" << id << " splits to #" << child1.getId() << " and #" << child2.getId() << endl;
		CellQueue.push(child1);		//将第一个子细胞压入优先级队列
		CellQueue.push(child2);		//将第二个子细胞压入优先级队列
	}
};

int Cell::count = 0;

int main()
{
	srand(static_cast<unsigned>(time(0)));//种子
	int t;	//模拟时间长度
	cin >> t;
	CellQueue.push(Cell(0));	//将第一个细胞压入优先级队列

	while (CellQueue.top().getSplitTime() <= t) {
		CellQueue.top().split();	//模拟下一个细胞的分裂
		CellQueue.pop();		//将刚刚分裂的细胞弹出
	}
	system("pause");
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值