【发布时间】:2018-01-22 20:26:43
【问题描述】:
您好,我正在为我的任务创建一个队列,并且我不断得到“4 4 4 4 4”的输出。我不确定我个人是否在纸上做错了队列,或者我是否在程序中搞砸了。我只是想确认队列是否真的输出到该输出。我包括了入队和出队文件。谢谢你
#include <iostream>
#include <cstdlib>
using namespace std;
const int MAX_SIZE = 100;
class QueueOverFlowException
{
public:
QueueOverFlowException()
{
cout << "Queue overflow" << endl;
}
};
class QueueEmptyException
{
public:
QueueEmptyException()
{
cout << "Queue empty" << endl;
}
};
class ArrayQueue
{
private:
int data[MAX_SIZE];
int front;
int rear;
public:
ArrayQueue()
{
front = -1;
rear = -1;
}
void Enqueue(int element)
{
// Don't allow the queue to grow more
// than MAX_SIZE - 1
if ( Size() == MAX_SIZE - 1 )
throw new QueueOverFlowException();
data[rear] = element;
// MOD is used so that rear indicator
// can wrap around
rear = ++rear % MAX_SIZE;
}
int Dequeue(int n)
{
if ( isEmpty() )
throw new QueueEmptyException();
int ret = data[front];
// MOD is used so that front indicator
// can wrap around
front = ++front % MAX_SIZE;
return ret;
}
int Front()
{
if ( isEmpty() )
throw new QueueEmptyException();
return data[front];
}
int Size()
{
return abs(rear - front);
}
bool isEmpty()
{
return ( front == rear ) ? true : false;
}
};
int main()
{
ArrayQueue q;
int x =2;
int y = 4;
q.Enqueue(x);
q.Enqueue(y);
q.Dequeue(x);
q.Enqueue(x+5);
q.Enqueue(16);
q.Enqueue(x);
q.Enqueue(y-3);
cout << "Queue: ";
while(!q.isEmpty())
{
q.Dequeue(y);
cout<<" " << y;
}
}
【问题讨论】:
-
您只是在循环的每次迭代中输出 y 的值。
-
OT:
throw new QueueEmptyException()应该是throw QueueEmptyException(),你可以很容易地让QueueEmptyException扩展std::runtime_error。异常构造函数中的cout << ...不应存在 -
int Dequeue(int n)为什么要带参数?您是否打算在实施中使用它? -
为什么
QueueOverFlowException不继承自std::exception?不是说它应该;只是好奇作为“为什么不”的原因.. -
rear = ++rear % MAX_SIZE;看起来很奇怪。我可以让你感兴趣一个漂亮、易于关注的rear = (rear+1) % MAX_SIZE;吗?
标签: c++ queue implementation