闲来无事,晚上有偷了个闲实现了队列。
头文件:
#pragma once
#define MAX 20
class QueueRecord
{
public:
QueueRecord();
~QueueRecord(void);
int IsEmpty();
int IsFull();
void MakeEmpty();
void Enqueue(int x);
int FrontOnly();
void Dequeue();
int FrontAndDequeue();
private:
int Capacity;
int Front;
int Rear;
int Size;
int Array[MAX];
};
.cpp:
#include "StdAfx.h"
#include "QueueRecord.h"
#include <stdexcept>
using std::runtime_error;
QueueRecord::QueueRecord():Size(0),Front(1),Rear(0),Capacity(MAX)
{
}
QueueRecord::~QueueRecord(void)
{
//delete [] Array;
}
int QueueRecord::IsEmpty()
{
return Size == 0;
}
int QueueRecord::IsFull()
{
return Size == Capacity;
}
void QueueRecord::MakeEmpty()
{
Size = 0;
Front = 1;
Rear = 0;
}
void QueueRecord::Enqueue(int x)
{
if (IsFull())
{
runtime_error("Full Queue");
}
else
{
if (++Rear==Capacity)
{
Rear = 0;
}
Size++;
Array[Rear] = x;
}
}
void QueueRecord::Dequeue()
{
if (IsEmpty())
{
runtime_error("Empty Queue");
}
else
{
if (++Front==Capacity)
{
Front = 0;
}
Size--;
}
}
int QueueRecord::FrontOnly()
{
if (IsEmpty())
{
return 0;
}
return Array[Front];
}
int QueueRecord::FrontAndDequeue()
{
if (IsEmpty())
{
runtime_error("Empty Queue");
return 0;
}
else
{
int x = Array[Front];
if (++Front==Capacity)
{
Front = 0;
}
Size--;
return x;
}
}
已经亲测,可以用。
几点说明:
1.为了省事,没有用动态数组。因为在前文中已经提到,指针实现的动态数组不能用下标进行赋值(我也不知道原因,但是在我的VS2010上就是不行),所以就固定了大小,有利有弊,目测弊要大于利啊……
2..cpp中有一行“//delete [ ] Array; ”,被我注释了,这里说个说明,也是无意中发现的。本来是觉得开了一个数组,用完之后释放内存的(估计我当时梦游以为我用的是动态数组呢),然后调试的时候,显示“其原因可能是堆被损坏,这说明 中或它所加载的任何 DLL 中有 Bug”,我不知道是怎么回事,就google了一下,找到了答案。原来局部变量开辟的是栈,而用new开辟的是堆空间,所以用delete释放内存的时候就会报DLL的错误。详情请戳这里:点击打开链接 这里有详细的讨论。
也算是无意中发现的一个秘密吧,也许以后在用DLL开辟空间给应用程序的时候犯这样的错误呢,是吧!
好吧,就到这里结束吧~~