首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

queue删除队首有关问题

2012-03-24 
queue删除队首问题这是别人的程序修改而成的。要求删除从队首进行,而添加从队尾进行,但是运行后发现删除也

queue删除队首问题
这是别人的程序修改而成的。
要求删除从队首进行,而添加从队尾进行,但是运行后发现删除也从队尾进行!是不是删除队首函数有问题,帮忙看下,谢谢!
#include <iostream.h>
extern "C" {void exit(int);}
const int nDefaultQueueSize = 50;
template <class T>//
class Queue {
private:
  T *qlist; //存放队列元素的指针(数组)
  int size; //队列大小(容量)
  int front; //队首位置
  int rear; //队尾位置(最后一个元素的下一位置)
  int count; //队列中元素的个数
public:
Queue(int initSize=nDefaultQueueSize) 
{
if (initSize < 1)
initSize = nDefaultQueueSize;
qlist = new T[initSize];
if (!qlist)
{
cerr << "存储空间分配失败,应用程序将终止!"<< endl;//好像很高级
  exit(1);
  }
front=0;
  rear=0;
  count=0;
  size=initSize;
  }
  //析构函数
  ~Queue()
{
if (qlist) delete [] qlist;
front = 0;
rear = 0;
  count = 0;
  size = 0;
  }
  //判断队列是否为空
  bool QEmpty() 
{
  return count == 0;
  }
  //判断队列是否已满
  bool QFull() 
{
  return count == size;
  }
  void dump()
{
if(QEmpty())
cerr<<"队列为空,无法再删除!"<<endl;
else

cout<<"队列从头到尾为:\n";
for(int i=0;i<count;i++)
cout<<'\t'<<qlist[i]<<'\n';
}
  //队列长度
  int QLength() 
{
  return count;
  }
  //队尾插入(追加)元素
  void QInsert(const T &item) 
{
if (count == size)
{
cerr << "队列已满,无法再追加元素。"<< endl;
  return;
  }
  count ++;
  qlist[rear] = item;
  rear = (rear + 1) % size; //rear始终指向最后一个元素的下一个位置
cout<<"增加元素"<<item<<endl;
  }
////////////////////////////////////////////////////////////////////////////////////
  //删除队首元素?????????????????? //
//删除的不是队尾而是队首 ????????????? //
  T QDelete(T &data) //it sames that there are something wrong! //
{ //
  if (count > 0) //  
{ //  
  data = qlist[front]; // 
  count --; //
  front = (front+1) % size; //front移向下一位置 // 
cout<<"@执行删除队首元素操作!"<<endl;//删除后给出删除提示 //
  } //
  else //
  cerr << "队列已空,无法继续删除。" << endl; //
  return data; //
  } //
////////////////////////////////////////////////////////////////////////////////////
  //读取队首元素
  T QFront(T &data)
{
  if (count > 0)
  data = qlist[front];
  else 
  cerr << "队列为空,无法读取队首元素的值。" << endl;
  return data;
  }
  //清空队列
  void ClearQueue() 


{
  front = 0;
  rear = 0;
  count = 0;
cout<<"@执行清空操作!"<<endl;
  }
};

void main()
{
  Queue<int> Q;
  int e;
Q.QInsert(1);
Q.QInsert(2);
cout << "front : " << Q.QFront(e) << endl;
Q.QInsert(3);
Q.dump();
Q.QDelete(e);
Q.dump();
Q.ClearQueue();
  Q.dump();


}

[解决办法]
void dump() 

if(QEmpty()) 
cerr < <"队列为空,无法再删除!" < <endl; 
else 

cout < <"队列从头到尾为:\n"; 
for(int i=front;i <rear;i++) //原来这句代码造成的问题,这样改就对了。
cout < < '\t ' < <qlist[i] < < '\n '; 


[解决办法]
STL就是Standard Template Library,标准模板库。包含进去就可以用了
可以象这样来定义一个STL的list: 
#include <string>
#include <list>
int main (void) 
{
list<string> Milkshakes;
return 0;
}

热点排行