Я потратил на это много времени и сил, но это вызывает разочарование. У меня есть реализация этой очереди в книге Роба Седжуика, но когда я попытался ее протестировать, функция 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;
}
заведите [Minimal, Complete, Проверяемость Пример] (HTTP://stackoverflow.com/help/mcve) –
'int size = 0',' QUEUE q (size) 'Сколько элементов может содержать очередь? – NathanOliver
Пожалуйста, запишите название вопроса. –