如何获得矢量队列的前面或顶部元素?

时间:2016-12-06 06:27:14

标签: c++ vector linked-list queue

我没有提供完整的代码,因为它很长,我只需要帮助处理****区域的小部分。我似乎无法使用front()或top()来获取队列的顶部元素。我尝试使top()函数列表不断出错:1)class List没有名为' top'这意味着我没有列表中的功能顶部,当我说它2)没有匹配'运营商='在printer_cpu [i] = SList :: top(),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 ****
              }

        }
}

2 个答案:

答案 0 :(得分:0)

看起来你错过了一个星号,因为你需要返回类型指针,因为那是什么头。 你应该

node<T> * top() 
{
  ...
}

您还需要重载=运算符,因为您正在尝试将类型PCB与类型节点*进行比较。

答案 1 :(得分:0)

好吧,我在纠正了一些错误后成功编译了你的代码。

我没有遇到class List has no memeber named 'top'问题。

然后,您的top()函数会返回head的值,因此您应将其更改为:node<T>* top(),因为head是指向node<T>的指针。< / p>

您遇到no match for 'operator='错误的原因是printer_cpu[i]的类型为PCB,而PQ[i].top()的类型应为node<T>*

我还发现您发布的代码在}之前缺少int main()