我在实施优先级队列时遇到问题。每当我执行以下代码时,文本文件中的第一项打印,但程序在此之后停止。
void loadCustomerData(){
double simClock, avgSelectionTime;
int items;
ifstream myfile ("arrival.txt");
if (myfile.is_open()){
while ( myfile >> simClock >> items >> avgSelectionTime){
Customer cust(simClock, items, avgSelectionTime) ;
cout << cust << endl;
Event e(EventType::Arrival, simClock, cust);
events.enqueue(e);
}
myfile.close();
}else
throw(1);
}
如果我注释掉在PriorityQueue“事件”中排队的行,它们将全部打印出来。所以我认为enqueue方法存在问题。我猜它与我的节点设置方式有关,因为它之前抛出了编译错误。如果有人能告诉我哪里出错了,那将非常感激。这是我的优先级队列的代码:
#pragma once
#include <iostream>
using namespace std;
template <class T> class MyPriorityQueue
{
private:
struct Node{
Node * next;
double priority;
T value;
Node(T value, double priority, Node * next = NULL){
this->next = next;
this->value = value;
this->priority = priority;
}
};
Node *head;
public:
int size = 0;
MyPriorityQueue(){
head = NULL;
size = 0;
}
~MyPriorityQueue(){
if(head){
Node * lead = head->next;
Node * follow = head;
while(lead){
delete(follow);
follow = lead;
lead = lead->next;
}
delete(follow);
}
}
void enqueue(T item){
Node *temp, *q;
temp->priority = item.simTime;
temp->value = item;
if (head == NULL || temp->priority < head->priority){
temp->next = head;
head = temp;
size ++;
}
else{
q = head;
while (q->next != NULL && q->next->priority <= temp->priority){
q=q->next;
temp->next = q->next;
q->next = temp;
size ++;
}
}
}
Event dequeue(){
Node *temp;
temp = head;
head = head->next;
return temp->value;
free(temp);
size --;
}
};