紫书章五习题九 Bug Hunt UVA 1596

来源:互联网 发布:淘宝拍卖烂尾楼 编辑:程序博客网 时间:2024/05/21 06:39

题意:一共有两种bug需要你找(自己不要想太多)
一共有两种操作
1.数组的声明,这个是没有bug的。注意只是声明,没有初始化
2.赋值操作 a[10]=2或a[10]=a[2]。这里bug会出现在用了没有初始化的值,超过数组的大小,用了没有声明的变量
还学到了
temp.find_first_of(‘[‘)//返回第一个[的下标
temp.find_last_of(‘]’)//返回最后一个】的下标
如果find没有找到值得话,就为string::npos
然后还有一个输入流的使用~

#include <iostream>#include <cstring>#include <algorithm>#include <cstdio>#include <cmath>#include <vector>#include <set>#include <map>#include <queue>#include <sstream>using namespace std;map<string , int > Map1;//里面存被定义了的数组及长度map<string, map<int ,int > > Map2;//数组对应的相应下标有没有被初始化int cheak(string temp){    if(temp[0]>='0'&&temp[0]<='9')    {        stringstream ss;        ss<<temp;        int len;        ss>>len;        return len;    }    else    {        string aname=temp.substr(0,temp.find_first_of('['));        string ain=temp.substr(temp.find_first_of('[')+1,temp.find_last_of(']'));        int i=cheak(ain);        if(i<0) return -1;        if(Map1.count(aname)==0)            {return -1;}        else        {            if(Map2[aname].count(i)==0)                {return -1;}            else return Map2[aname][i];        }    }}int read(){    string str;    int num=0,ans=0;    while(getline(cin,str))    {        if(str=="."&&num==0)            return 0;        else if(str==".")        {            printf("%d\n",ans);num=0;            ans=0;            Map1.clear();            Map2.clear();        }        else{            num++;            if(ans==0)            {                if(str.find("=")!=string::npos)                {                    string arr=str.substr(0,str.find("="));                    string brr=str.substr(str.find("=")+1);                    string aname = arr.substr(0,arr.find_first_of("["));                    string ain = arr.substr(arr.find_first_of("[")+1,arr.find_last_of("]"));                    int i=cheak(ain);                    int j=cheak(brr);                    int flag=0;                    if(i<0||j<0) ans=num;                    else if(Map1.count(aname)==0)                        ans=num;                    else                    {                        if(Map1[aname]<i+1)                            ans=num;                        else                            Map2[aname][i]=j;                    }                }                else{                    string aname=str.substr(0,str.find_first_of("["));                    string anum=str.substr(str.find_first_of("[")+1,str.find_last_of("]")-str.find_first_of("[")-1);                    stringstream ss;                    ss<<anum;                    int len;                    ss>>len;                    Map1[aname]=len;                }            }        }    }}int main(){   //freopen("E:\\input.txt","r",stdin);    while(read())    {    }    return 0;}
0 0
原创粉丝点击