プレーン・アレイを使用してキューを実装するには、循環的に処理します。つまり、配列内の空き領域がなくなると、0に折り返します。フロント・リアのレコードをあなたは注意します。 (Xは、キュー内のアイテムを表している)の例としては:
// Rear is where to enqueue into, Front is where to dequeue from
Empty Array:
| - - - |
Front = -1, Rear = 0
Enqueue()
| X - - |
Front = 0, Rear = 1
Enqueue()
| X X - |
Front = 0, Rear = 2
Dequeue()
| - X - |
Front = 1, Rear = 2
Enqueue()
| - X X |
Front = 1, Rear = 0 // Looped around
Dequeue()
| - - X |
Front = 2, Rear = 0
Enqueue()
| X - X |
Front = 2, Rear = 1
あなただけの周りにラップする剰余演算を使用する必要があります。もちろん、これはサイズが限られています(要素が足りなくなると、より多くのメモリを割り当てる必要があります)が、配列を扱うときに得られるものです。ここで
は(私は全くそれをチェックしていない)スタートとしていくつかのコードです:
// Private class variables:
// These should be set in the constructor of your queue class
unsigned int rear = 0; // back of the queue
unsigned int front = -1; // front of the queue
unsigned int numStored = 0;
unsigned int length;
Object* array = new Object[length];
QueueAr::Enqueue(Object& obj)
{
if (front == rear)
{
// Throw an exception: queue is full!
}
else
{
array[rear] = obj; // Insert the object at the back
rear++;
rear = rear % length;
numStored++;
}
}
// For kicks, here's the queue code
QueueAr::Dequeue(Object& obj)
{
if (numStored == 0)
{
// Throw an exception: queue is empty!
}
front++;
front = front % length;
numStored--;
}
STLの使用は許可されていますか?あるいは、普通の配列を使っていますか? – strager
あなたの例では、prov、r、f、nとは何ですか?あなたはあなたのクラスのボディを投稿できますか? – strager
私はリスト* Object = new Object [10]で割り当てられたリストを使用しています。私はこれで動作する必要があります。 – brsunli