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

Pop函数的bug,没有招到,该怎么处理

2012-05-09 
Pop函数的bug,没有招到C/C++ code#include stdafx.h#include iostreamusing namespace std#define MA

Pop函数的bug,没有招到

C/C++ code
#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个元素的时候,程序就会终止,跟踪很多次,都没有发现问题 



[解决办法]
for(i=0; i<cq.size(); i++)
i在增大,cq.size()在减小,当然5次就结束了。

改成while( ! cq.IsEmpty() )试试。
[解决办法]
探讨
for(i=0; i<cq.size(); i++)
i在增大,cq.size()在减小,当然5次就结束了。

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

热点排行