优先队列 PriorityQueue (用堆实现的)

普通队列是一种先进先出的数据结构。数据元素附加在队尾,从队首删除。在优先队列中,每个元素都赋予一个优先级。高优先级的元素优先访问删除。例如,医院按病人的优先级分配急救室;具有最高优先级的病人先被安排进入急救室。

程序清单 PriorityQueue.h

<div style="text-align: left;"><span style="font-family: 'Microsoft YaHei'; text-align: center; background-color: rgb(255, 255, 255);"></span></div>#ifndef PRIORITYQUEUE_H_INCLUDED
#define PRIORITYQUEUE_H_INCLUDED
#include "Heap.h"


template<typename T>
class PriorityQueue{
public:
    PriorityQueue();
    void enqueue(T element) ;
    T dequeue() throw (runtime_error);
    int getSize();
private:
    Heap<T> heap;
};


template<typename T>
PriorityQueue<T>::PriorityQueue(){
}


template<typename T>
void PriorityQueue<T>::enqueue(T element){
    heap.add(element);
}


template<typename T>
T PriorityQueue<T>::dequeue() throw (runtime_error){
    return heap.remove();
}


template<typename T>
int PriorityQueue<T>::getSize(){
    return heap.getSize();
}


#endif // PRIORITYQUEUE_H_INCLUDED<u>
</u>

程序清单 TestPriorityQueue.cpp


#include<iostream>
#include "PriorityQueue.h"
using namespace std;

class Patient{
public:
    Patient(string name, int priority){
        this->name = name;
        this->priority = priority;
    }

    bool operator<(Patient &secondPatient){           //运算符重载
        return (this->priority < secondPatient.priority);
    }

    bool operator>(Patient &secondPatient){         //运算符重载

        return (this->priority > secondPatient.priority);
    }
    string getName(){
        return name;
    }
    int getPriority(){
        return priority;
    }

private:
    string name;
    int priority;
};

int main(){
    //Queue of patients
    PriorityQueue<Patient> patientQueue;
    patientQueue.enqueue(Patient("John", 2));
    patientQueue.enqueue(Patient("Jim", 1));
    patientQueue.enqueue(Patient("Tim", 5));
    patientQueue.enqueue(Patient("Cindy", 7));

    while(patientQueue.getSize() > 0){
        Patient element = patientQueue.dequeue();
        cout<<element.getName()<<" (priority: "<<element.getPriority()<<")"<<endl;
    }
}<u>
</u>


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值