我没有放完整的代码,因为它很长,我只需要帮助一小部分,也就是****区域。我似乎无法使用 front() 或 top() 来获取队列的顶部元素。我尝试使 top() 函数列表不断出现错误:1) 类 List 没有名为“top”的成员,这意味着我在列表中没有函数 top,当我创建它时它说 2) 不匹配“operator=” ' in printer_cpu[i] = SList::top() with T=PCB]()'
template <class T>
class node{
public:
T data;
node *next;
};
template <class T>
class List{
node<T> *head;
node<T> *tail;
public:
List()
{
head = tail = NULL;
}
bool isEmpty()
{
if(head == NULL) return true;
else return false;
}
void enqueue(T new_data){
node<T> *temp = new node<T>;
temp->data = new_data;
temp->next = NULL;
if(isEmpty()){
head = temp;
tail = temp;
}
else{
tail->next = temp;
tail = temp;
}
}
void dequeue(){
if(isEmpty())
{
cout << "The list is already empty" << endl;
}
node<T>* temp;
if(head == tail){
temp->data=head->data;
delete head;
head = tail = NULL;
}
else{
temp->data = head->data;
head = head->next;
delete temp;
}
}
node<T> top() // need help here ****
{
return head;
}
void display(){
node<T> *current = head;
while(current != NULL){
cout << current->data << endl;
current = current->next;
}
}
};
struct PCB
{
int ProcessID;
int ProcessorSize;
int priority;
string name;
};
typedef List<PCB> printing;
typedef List<PCB> disk;
void gen(vector<printing> &printer_queue,string printer_name[], int printers)
{
for(int i = 0; i < printers; i++)
{
int num = i+1;
ostringstream convert;
convert << num;
printer_name[i] = "p" + convert.str();
printer_queue.push_back(printing());
}
int main()
{
int numOfPrinter = 5;
string interrupt;
cin >> interrupt;
PCB cpu;
PCB printer_cpu[numOfPrinter];
string printer_name[numOfPrinter];
vector<printing> PQ;
gen(PQ,printer_name,numOfPrinter);
for(int i = 0; i < numOfPrinter; i++)
{
if(interrupt == printer_name[i])
{
cout << "Enter a name for this printer file: " << endl;
cin >> cpu.name;
PQ[i].enqueue(cpu);
printer_cpu[i] = PQ[i].top(); //need help here ****
}
}
}
最佳答案
看起来你少了一个星号,因为你需要返回指针类型,因为这就是 head 。 你应该有
node<T> * top()
{
...
}
您还需要重载 = 运算符,因为您正试图将类型 PCB 与类型节点 * 进行比较。
关于c++ - 如何获取 vector 队列的前端或顶部元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40989080/