我已经定义了一个实现队列的模板类。
我插入int值:0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
当在屏幕队列内容中显示时,我得到值:
0 1 2 3 4 5 6 7 10 11 12 13 14 15 16。
我不明白为什么会有这种差异。你能帮我吗?
// Queue.h文件
template <class T> class Queue
{
private:
int numElements;
T* chain;
int limit;
public:
// Constructor
Queue (int);
void PutElement(T);
T GetElement();
void Print();
};
// Class Constructor.
template <class T> Queue<T>::Queue (int pNumElements)
{
numElements = pNumElements;
chain = new T[numElements];
limit = 0;
};
// Member functions.
template <class T> void Queue<T>::PutElement (T pElement)
{
if (limit < numElements)
chain[limit++] = pElement;
else
cout << "ERROR WHEN TRY TO INSERT A NEW ELEMENT: Queue is full.\n";
};
template <class T> T Queue<T>::GetElement()
{
T tempElement;
if (limit == 0)
{
cout << "ERROR: Queue is empty\n";
return NULL;
}
tempElement = chain[0];
if (limit >= 2)
for (int pos=1; pos < limit; pos++)
chain[pos-1] = chain[pos];
limit--;
return tempElement;
};
template <class T> void Queue<T>::Print()
{
cout << "QUEUE CONTENTS: ";
for (int pos=0; pos<limit; pos++)
if (pos < limit-1)
cout << chain[pos] << ", ";
else
cout << chain[pos] << endl;
};
// main.cpp file:
#include <iostream.h>
#include "Queue.h"
void main()
{
cout << "\nint values QUEUE\n";
Queue <int> q1(15); // Max number of elements in queue is 15.
for (int aux=0; aux<17;aux++)
q1.PutElement(aux);
q1.Print();
for (aux=1; aux<20;aux++)
cout << "Queue element number " << aux << " is : " << q1.GetElement() << endl;
}"
// Screen result:
int values QUEUE
ERROR WHEN TRY TO INSERT A NEW ELEMENT: Queue is full.
ERROR WHEN TRY TO INSERT A NEW ELEMENT: Queue is full.
QUEUE CONTENTS: 0, 1, 2, 3, 4, 5, 6, 7, 10, 11, 12, 13, 14, 15, 16
Queue element number 1 is : 0
Queue element number 2 is : 1
Queue element number 3 is : 2
Queue element number 4 is : 3
Queue element number 5 is : 4
Queue element number 6 is : 5
Queue element number 7 is : 6
Queue element number 10 is : 7
Queue element number 11 is : 10
Queue element number 12 is : 11
Queue element number 13 is : 12
Queue element number 14 is : 13
Queue element number 15 is : 14
Queue element number 16 is : 15
Queue element number 17 is : 16
ERROR: Queue is empty
Queue element number 20 is : 0
ERROR: Queue is empty
Queue element number 21 is : 0
ERROR: Queue is empty
Queue element number 22 is : 0
ERROR: Queue is empty
Queue element number 23 is : 0"
答案 0 :(得分:0)
也许我对你要做的事感到困惑,但是你没有插入值为0到14的int。在你的主函数中,你说那就是
for (int aux=0; aux<17;aux++)
q1.PutElement(aux);
这是输入值为0到16的整数......如输出所示。