Pop函数的bug,没有招到

baitiane7100 2012-05-08 01:08:58
#include "stdafx.h"
#include <iostream>

using namespace std;

#define MAXSIZE 100


class CircleQueue
{

int arr[MAXSIZE ];
int front,rear;

public:

CircleQueue()
{
front=0;
rear=0;

};

bool IsEmpty() const
{
return front==rear;

}

bool IsFull() const
{

return front==(rear+1)%MAXSIZE ;

}


void Push(int val)
{
if(! IsFull())
{
rear=(rear+1)%MAXSIZE;
arr[rear-1]=val;
}

}


int Pop() throw(out_of_range)
{
if( ! IsEmpty() )
{
{
int tmp=front;
front=(front+1)%MAXSIZE;
return arr[tmp];
}
}
else
throw out_of_range("队列空");
}

int size() const
{
return (rear+MAXSIZE-front)%MAXSIZE;
}
};


int main()
{

CircleQueue cq;

int i;

int const count=10;

for(i=0; i<count; i++)
{
cq.Push(i);
}
cout<<"循环队列的元素为:"<<cq.size()<<endl;


int size=cq.size();


for(i=0; i<cq.size(); i++)
{
try
{
cout<<cq.Pop()<<endl;
}
catch(out_of_range e)
{
cout<<e.what()<<endl;
}
}

return 0;
}




弹出第5个元素的时候,程序就会终止,跟踪很多次,都没有发现问题

...全文
96 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
W170532934 2012-05-08
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]
for(i=0; i<cq.size(); i++)
i在增大,cq.size()在减小,当然5次就结束了。

改成while( ! cq.IsEmpty() )试试。
[/Quote]
你在Pop的时候没有修改size。你会犯错的哦
zjs100901 2012-05-08
  • 打赏
  • 举报
回复
for(i=0; i<cq.size(); i++)
i在增大,cq.size()在减小,当然5次就结束了。

改成while( ! cq.IsEmpty() )试试。

64,648

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧