優先隊列 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>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章