请帮助在此代码中找到错误

时间:2015-03-27 18:24:22

标签: c++

我花了很多时间和精力,但这令人沮丧。我在Rob Sedgewick的书中有这个队列实现,但是当我尝试测试它时,get()函数不起作用。它总是显示队列为空。

#include <iostream>

using namespace std;

class QUEUE {
private:
    int* q;
    int N;
    int head;
    int tail;
public:
    QUEUE(int maxN) {
        q = new int[maxN + 1];
        N = maxN + 1; 
        head = N; 
        tail = 0;
    }   

    bool empty() const {
        return (head % N == tail);
    }

    void put(int item) {
        q[tail++] = item; 
        tail = tail % N;
    }

    int get() {
        head = head % N; 
        return q[head++];
    }

    void peekAll() { 
        cout << endl; 
        int i = head % N;
        while (i != tail) {
            cout << q[i] << " ";
            i = (i + 1) % N;
        }
        cout << endl;
    }
};


int main() {
    int size = 0, capacity;
    cout << "\nPlease enter the maximum queue size\n";
    cin >> capacity;
    QUEUE q(size);
    cout << "\nInstruction Menu: \n\n"
        << "P x: puts x into queue\n"
        << "G :  outputs the element at the head of the queue, and removes this element from the queue\n"
        << "E : outputs empty if queue is empty; otherwise not empty\n"
        << "F : displays the entire content of the queue in first - in first - out order; no change in the queue\n"
        << "X: Exit Program\n";
    char c;
    int i;
    do {
        cout << "\n\nPlease enter the input instructions: \n";
        cin >> c;
        switch (c) {
            case 'P': cin >> i;
                      if (size < capacity) {
                          q.put(i);
                          size++;
                          cout << endl << i << " successfully inserted\n";
                      } else cout << "\nThe queue is full.Couldn't insert " << i << endl;
                      break;
            case 'G': if (!q.empty()) {
                         cout << endl << q.get() << endl;
                         size--;
                      } else cout << "\nThe queue is empty.\n";   
                      break;
            case 'E': if (q.empty()) cout << "\nEmpty\n";
                      else cout << "\nNot Empty\n";
                      break;
            case 'F': q.peekAll();
                      break;
            case 'X': cout << "\nExiting program...\n";
                      break;
            default: cout << "\nInvalid input entered. Try again.\n";
        }
    } while (c != 'X');
    system("pause");
    return 0;
}

2 个答案:

答案 0 :(得分:2)

int maxN是队列的容量,因此您的队列容量为0 所以它总是空着的。

你应该做

QUEUE q(capacity);

答案 1 :(得分:2)

队列的大小为0

QUEUE q(size);  <-- size = 0

将其更改为:

 QUEUE q(capacity);   <-- whatever user enters, will help if you check for user input