• 404.00 KB
  • 2022-04-22 11:45:58 发布

《程序设计》习题解答.doc

  • 49页
  • 当前文档由用户上传发布,收益归属用户
  1. 1、本文档共5页,可阅读全部内容。
  2. 2、本文档内容版权归属内容提供方,所产生的收益全部归内容提供方所有。如果您对本文有版权争议,可选择认领,认领后既往收益都归您。
  3. 3、本文档由用户上传,本站不保证质量和数量令人满意,可能有诸多瑕疵,付费之前,请仔细先通过免费阅读内容等途径辨别内容交易风险。如存在严重挂羊头卖狗肉之情形,可联系本站下载客服投诉处理。
  4. 文档侵权举报电话:19940600175。
'C++程序设计习题解答(王挺)杂项1背包问题1趣味题1打印万年历2期末考试题3求解1□23□4□56□7□8□9=1004Chapter44P103T04104P103T04114P103T04125P103T04135输出不大于的Fibonacci数列5Stein算法求最大公约数--移位法5P102T04156P102T04166P102T04176P102T04197P102T04207P102T04217Chapter57p136T5.57p136T5.68p136T5.68p136T5.108p136T5.118p137T5.149p137T5.169p137T5.199Chapter69求组合算法9P159T6.310P159T6.410P159T6.410p159T6.1111p159T6.1211p159T6.1811p159T6.2012Chapter712p195T70612p195T70712p195T70812p195T70913P195T71014P195T71114P196T71314Chapter815p222T80315p222T08030415p222T8517p222T8060917附加18II C++程序设计习题解答(王挺)Chapter918P241T9.118P241T9.219P241T9.320P241T9.521补充22Chapter1123p288T11.223P289T11.923//使用结构实现栈24//利用类实现栈数据结构25Chapter1226P305T120426p305T120527P306T120627P306T120729P306T120829Chapter1330P334T13附加题30P334T130331P334T130432P335T130533P335T130634p335T130734p336T130835P336T130936向量矩阵综合应用37Chapter1440P373T140540Chapter1642P422T160242P422T160342P423T160543P422T1605-243Chapter1744P436T170644P436T170745P436T170945P436T171045II C++程序设计习题解答(王挺)杂项/*背包问题背包问题的求解,求解除所有的可能解法,非递归*/#include#includeusingnamespacestd;typedefintDataElem;classStack{private:intsize;inttop;DataElem*elem;public:Stack(intsize);voidPush(DataEleme);voidPop(DataElem&e);boolEmpty();intTopPtr();int&operator[](inti){assert(i<=top);returnelem[i];}};intStack::TopPtr(){returntop;}Stack::Stack(intsize){elem=newDataElem[size];this->size=size;top=-1;}voidStack::Pop(DataElem&e){assert(top!=-1);e=elem[top--];}voidStack::Push(DataEleme){assert(top!=size-1);elem[++top]=e;}boolStack::Empty(){returntop==-1;}voidprint(Stack&s,DataElem*w){for(inti=0;i<=s.TopPtr();i++)cout<0&&k=0){s.Push(k);T-=w[k];}k++;}if(T==0)print(s,w);s.Pop(k);T+=w[k];k++;}while(!s.Empty()||k!=n);}voidmain(){DataElemw[]={1,2,3,4,5,6,7,8,9,10};knapsack(w,10/*背包大小,必须保证此值不小于数组w的元素中的最大值*/,sizeof(w)/sizeof(DataElem));}/*趣味题计算N!,要求打印出每一位*/#include#include#include47 C++程序设计习题解答(王挺)usingnamespacestd;typedefcharDataElem;//定义双向链表节点数据类型typedefstruct_tagNode{struct_tagNode*pre;DataElemdata;struct_tagNode*next;}NODE,*PNODE;voidmain(){PNODEhead,tail,cur;intn;//calculaten!cout<<"pleaseEnterannumbern";cin>>n;head=newNODE;head->data=1;head->pre=head->next="";tail=head;intprd,carry;struct__timeb64starttime,endtime;_ftime64(&starttime);for(inti=1;i<=n;i++){cur=tail;carry=0;while(cur){prd=cur->data*i+carry;cur->data=prd%10;//末位carry=prd/10;//进位cur=cur->pre;}while(carry)//链表上的所有节点和乘数相乘完毕后还有进位{cur=newNODE;cur->data=carry%10;cur->next=head;cur->pre="";head->pre=cur;head=cur;carry/=10;}}while(head){cout<data);cur=head;head=head->next;deletecur;}cout<#includeusingnamespacestd;voidmain(){intmm[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};char*monthname[]={"January","February","March","April","May","June","July","August","September","October","November","December"};inty,w,i,j;cout<<"pleaseinputyear:";cin>>y;if(!(y%400)||!(y%4)&&y%100)mm[2]=29;y--;w=y+y/4-y/100+y/400+1;w%=7;y++;for(i=1;i<13;i++){/*switch(i/3){case1:cout<<"ntt"<usingnamespacestd;classA{private:intage;char*name;public:A();A(A&a);A(char*str,intn);~A();voidoutputA();};A::A(A&a){age=a.age;name=newchar[strlen(a.name)+1];strcpy(name,a.name);}A::~A(){cout<<"Distructor"<usingnamespacestd;enumweekday{mon=1,tue,wed,thu,fri,sta,sun=0};char*strweek[]={"sun","mon","tue","wed","thu","fri","sta"};voidmain(){cout<usingnamespacestd;voidmain(){47 C++程序设计习题解答(王挺)char*suit[4]={"Hearts","Diamonds","Clubs","Spades"};cout<usingnamespacestd;voidmain(){inta[3]={0},*pa=a;char*pc;short*ps=(short*)pa;pc=(char*)pa;for(inti=0;i<12;i++)*(pc+i)=1;cout<#includeusingnamespacestd;voidmain(){inta[7]={1,23,4,56,7,8,9};intsign[6];inti;intsum;for(i=61;i<64;i++){sum=a[0];for(intj=0;j<6;j++){sign[j]=(i&(1<y,则输出x-y,否则,输出y-x设计一个程序,输出x与y的差的绝对值,不能使用abs函数*/#includeusingnamespacestd;voidmain(){doublex,y;cin>>x>>y;if(x>y)cout<#include//requiredbylog10()usingnamespacestd;voidmain(){inta,b,k;cin>>a;//判断是几位的最简洁算法//cout<99999||a<0){cout<<"yourEnteristoobig"<usingnamespacestd;voidmain(){inta,max,n;n=10;cin>>max;n--;while(n>0){cin>>a;if(max#include#includeusingnamespacestd;#defineEPSLON1e-10voidmain(){floata,b,c;cin>>a>>b>>c;assert(fabs(a)>EPSLON);assert(b!=0);assert(c!=0);if(a+b>c&&a+c>b&&b+c>a)cout<<"Yes"<usingnamespacestd;voidmain(){intf1=1;intf2=1,f3;cout<100)break;cout<y,我们注意到x+y和x-y是两个偶数,则有g_c_d(x+y,x-y)=2*g_c_d((x+y)/2,(x-y)/2),那么g_c_d(x,y)与g_c_d(x+y,x-y)以及g_c_d((x+y)/2,(x-y)/2)之间是不是有某种联系呢?为了方便我设m=(x+y)/2,n=(x-y)/2,容易发现m+n=x,m-n=y。设a=g_c_d(m,n),则m%a=0,n%a=0,所以(m+n)%a=0,(m-n)%a=0,即x%a=0,y%a=0,所以a是x和y的公约数,有g_c_d(m,n)<=g_c_d(x,y)。再设b=g_c_d(x,y)肯定为奇数,则x%b=0,y%b=0,所以(x+y)%b=0,(x-y)%b=0,又因为x+y和x-y都是偶数,跟前面一奇一偶时证明a是x的约数的方法相同,有47 C++程序设计习题解答(王挺)((x+y)/2)%b=0,((x-y)/2)%b=0,即m%b=0,n%b=0,所以b是m和n的公约数,有g_c_d(x,y)<=g_c_d(m,n)。所以g_c_d(x,y)=g_c_d(m,n)=g_c_d((x+y)/2,(x-y)/2)。我们来整理一下,对两个正整数x>y:1.均为偶数g_c_d(x,y)=2g_c_d(x/2,y/2);2.均为奇数g_c_d(x,y)=g_c_d((x+y)/2,(x-y)/2);2.x奇y偶g_c_d(x,y)=g_c_d(x,y/2);3.x偶y奇g_c_d(x,y)=g_c_d(x/2,y)或g_c_d(x,y)=g_c_d(y,x/2);现在我们已经有了递归式,还需要再找出一个退化情况。注意到g_c_d(x,x)=x,我们就用这个。*/unsignedintgcd(unsignedintx,unsignedinty){unsignedinti,j,t;if(x==0)returny;if(y==0)returnx;for(i=0;0==(x&1);x>>=1,++i);for(j=0;0==(y&1);y>>=1,++j);if(j>=1);}}/*P102T0415输出~156的二进制、进制、进制和进制的对照表*/#include#include#include//requiredbyclassstring.usingnamespacestd;#defineI156voidmain(){strings;//存储二进制的各个位inti=1,a;for(;i<=I;i++){a=i;cout<usingnamespacestd;voidmain(){inta,b,c,d;cin>>a>>b>>c>>d;if(a#includeusingnamespacestd;voidmain(){doublea,b,c;doubledelta;cout<<"PleaseEntera,b,c"<>a>>b>>c;if(fabs(a)<1e-10&&fabs(b)<1e-10)//a==0andb==0,Inputerror{cout<<"aandbarezero"<0)//twodifferenceroots{cout<<"hastworoots:"<usingnamespacestd;voidmain(){inta,i;cout<<"PleseEntera"<>a;for(inti=1;iusingnamespacestd;voidmain(){inta,sum;while(1){cout<<"PleseEntera"<>a;if(a<0)return;sum=0;while(a){sum+=a%10;a/=10;}cout<usingnamespacestd;voidmain(){intn1,n2,n3;intd1,d2,d3;n1=2;n2=3;d1=1;d2=2;doublesum=0;sum+=(double)n1/d1+(double)n2/d2;for(inti=0;i<18;i++){n3=n1+n2;d3=d1+d2;sum+=(double)n3/d3;n1=n2;d1=d2;n2=n3;d2=d3;}cout<#includeusingnamespacestd;intfactorialSum(intn){intsum=0;for(inti=1;i<=n/2;i++)if(n%i==0)sum+=i;returnsum;}voidmain(){intfs=0;for(inti=1;i<=400;i++){fs=factorialSum(i);for(intj=i;j<=400;j++){if(fs==j&&factorialSum(j)==i){cout<usingnamespacestd;voidtrans(intn,intbase){if(nusingnamespacestd;intreverse(intn,intbase){intsum=0;while(n){sum=sum*10+n%base;n/=base;}returnsum;}voidmain(){cout<#includeusingnamespacestd;doublef(doublex){return2*x*x*x-4*x*x+3*x-6;}doublef1(doublex){return6*x*x-4*x+3;}doublefun(doublex1,double(*f1)(double),double(*f2)(double)){doublex0;do{x0=x1;x1=x0-(*f1)(x0)/(*f2)(x0);}while(fabs(x1-x0)<1e-7);returnx1;}voidmain(){doublex0,x1;cout<<"pleaseEnterthex1"<>x1;cout<#includeusingnamespacestd;intisPrime(intn){if(n<=1)return0;if(n==2)return1;for(inti=2;i>n;for(inti=2;i<=n-2;i++)if(isPrime(i)&&isPrime(n-i))cout<usingnamespacestd;#definePI3.14159inlinevoidcircleArea(){doubleradius;cout<<"PleaseEnterRadius";cin>>radius;cout<usingnamespacestd;voidreverse(char*str){if(strlen(str)==1)cout<<*str;else{reverse(str+1);cout<<*str;}}voidmain(){reverse("abcd");}/*p137T5.19用递归方法和非递归方法输出Hermite前n项。*/#include#includeusingnamespacestd;doubleHermite(doublex,intn)//递归方法{if(n==0)return1;elseif(n==1)return2*x;elsereturn2*x*Hermite(x,n-1)-2*(n-1)*Hermite(x,n-2);}voidHermite1(doublex,intn)//非递归方法{doubleH0=1,H1=2*x,H2;cout<usingnamespacestd;#defineMAXN100inta[MAXN];voidcomb(intm,intk){inti,j;for(i=m;i>=k;i--){a[k]=i;if(k>1)comb(i-1,k-1);else{for(j=a[0];j>0;j--)printf("%4d",a[j]);printf("n");}}}voidmain(){47 C++程序设计习题解答(王挺)a[0]=3;comb(4,a[0]);}/*P159T6.3求n个数的均方差*/#includeusingnamespacestd;doubleaverage(doublea[],intn){doubleavg=0.0;for(inti=0;i#includeusingnamespacestd;voidmain(){constintn=5;inta[n][n];inti,j;intsum=0;srand((unsigned)time(NULL));for(i=0;i#includeusingnamespacestd;voidinputarr(inta[][2],intm,intn){for(inti=0;i<20;i++)for(intj=0;j<2;j++)a[i][j]=int(double(rand())/RAND_MAX*100);}voidoutputarr(inta[][2],intm,intn){for(inti=0;i<20;i++){for(intj=0;j<2;j++)cout<usingnamespacestd;voidmain(){staticinta[2][3]={1,2,3,4,5,6};staticintb[3][2];staticintc[2][2];staticintd[3][3];inti,j,k;for(i=0;i<2;i++)for(j=0;j<3;j++)b[j][i]=a[i][j];for(i=0;i<3;i++){for(j=0;j<2;j++)cout<usingnamespacestd;voidmain(){staticinta[13]={2,5,7,9,13,17,45,67,89,101,135,238};//数组大小比初始化的元素个数多一ints,i;cin>>s;for(i=11;;i--){if(s>=a[i]||i==-1){a[i+1]=s;break;}elsea[i+1]=a[i];}for(i=0;i<13;i++)cout<usingnamespacestd;voidmain(){staticinta[]={2,5,7,9,13,17,45,67,89,101,135,238};47 C++程序设计习题解答(王挺)intlen=sizeof(a)/sizeof(*a);intleft=0,right=len-1,middle;ints;cin>>s;while(leftusingnamespacestd;voidmain(){staticchars1[81]="China";staticchars2[81]="China";inti;for(i=0;s1[i]==s2[i]&&s1[i];i++);if(s1[i]==s2[i])cout<<"Equal"<s2[i])cout<<"s1s2"<usingnamespacestd;intindex(constchar*str,charch){inti=0;for(;*(str+i);i++)if(*(str+i)==ch)returni;return-1;}intindex(constchar*str1,char*str2){for(inti=0;*(str1+i);i++){for(intj=0;*(str2+j);j++){if(*(str1+i+j)!=*(str2+j))break;}if(*(str2+j)==0)returni;}return-1;}voidmain(){char*s="thisisasample";char*str2="sample";cout<usingnamespacestd;voidprintstrarr(char**str,intn)//输出字符串数组{inti;for(i=0;iusingnamespacestd;typedefint(*FUN)(int,int);FUNf[4];//int(*f[4])(int,int);intf1(inta,intb){returna+b;}intf2(inta,intb){returna-b;}intf3(inta,intb){returna*b;}intf4(inta,intb){if(b!=0)returna/b;elsereturn0;}intindex(constchar*str,charch){inti=0;for(;*(str+i);i++)if(*(str+i)==ch)returni;return-1;}voidgetoperand(char*str){inta,b,L;if((L=index(str,"+"))!=-1){str[L]=0;a=atoi(str);str+=L+1;b=atoi(str);cout<<(*f[0])(a,b)<>str;getoperand(str);}/*P195T710*/#includeusingnamespacestd;voidinput(int*p,intn){for(inti=0;i>p[i];}return;}voidmain(){intn;cout<<"PleaseEnterStudentnumber"<>n;int*pscore;pscore=newint[n];input(pscore,n);inti;cout<<"PleaseEnterStudentNo."<>i;cout<usingnamespacestd;voidinput(int**p,intm,intn){inti,j;for(i=0;i>p[i][j];}}}voidprint(int**p,intm,intn){inti,j;for(i=0;i>m>>n;p=newint*[m];for(i=0;i#includeusingnamespacestd;char*ReplaceString(char*str,char*s1,char*s2){char*tmp=strstr(str,s1);if(tmp==NULL)return0;intlen=strlen(str);intlen1=strlen(s1);intlen2=strlen(s2);if(len1>=len2){while(*tmp++=*s2++);tmp--;while(*tmp=*(tmp+len1-len2))tmp++;}else{for(inti=0;iusingnamespacestd;staticintmonthday[][13]={{0,31,28,31,30,31,30,31,31,30,31,30,31},{0,31,29,31,30,31,30,31,31,30,31,30,31}};structDATE{intyear,month,day;};intisleapyear(constDATE&date){returndate.year%4==0&&date.year%100||date.year%400;}intday(constDATE&date){intsum=0;inti;intisleap=isleapyear(date);for(i=1;iusingnamespacestd;typedefstruct_DATE{intyear,month,day;}DATE;staticmonthday[][31]={{0,31,28,31,30,31,30,31,31,30,31,30,31},{0,31,29,31,30,31,30,31,31,30,31,30,31}};intdatecmp(DATE&date1,DATE&date2);intdaynum(DATE&date);intisleapyear(constDATE&date);intisleapyear(intyear);//返回两个日期之间的天数intdatediff(DATE&date1,DATE&date2){intsum=0,i;DATEd1=date1,d2=date2,d3;47 C++程序设计习题解答(王挺)if(datecmp(d1,d2)==1){d3=d1;d1=d2;d2=d3;}elseif(datecmp(d1,d2)==0)return0;if(isleapyear(d1))sum+=366-daynum(d1);elsesum+=365-daynum(d1);sum+=daynum(d2);for(i=d1.year+1;idate2.year)return1;elseif(date1.yeardate2.month)return1;elseif(date1.monthdate2.day)return1;elseif(date1.daymonthday[isleapyear(d)][d.month]){d.month++;if(d.month>12){d.year++;d.month=1;}n-=monthday[isleapyear(d)][d.month]-d.day;n--;d.day=1;}d.day+=n;returnd;}intisleapyear(constDATE&date){returndate.year%4==0&&date.year%100!=0||date.year%400==0;}intisleapyear(intyear){returnyear%4==0&&year%100!=0||year%400==0;}intvaliddate(DATE&date){if(!(date.year>=0&&date.year<=9999))return0;if(date.month<1||date.month>12)return0;if(date.day<1)return0;if(date.day<=monthday[isleapyear(date)][date.month])return1;return0;}intyear(DATE&date){returndate.year;}intmonth(DATE&date){returndate.month;}intday(DATE&date){returndate.day;}intdaynum(DATE&date){intsum=0;inti;intisleap=isleapyear(date);for(i=1;iusingnamespacestd;unioninteger{charc;shorts;inti;longl;};voidmain(){charc;shorts;inti;longl;integercomb;cin>>c>>s>>i>>l;comb.c=c;cout<<"char:"<#includeusingnamespacestd;structstudent{intnum;charname[20];floatscore[3];};//从文件中读取数据voidinput(student*std,intn){ifstreamfin("data.txt",ios::in);for(inti=0;i>std[i].name;fin>>std[i].num;fin>>std[i].score[0]>>std[i].score[1]>>std[i].score[2];}return;}//输出学生信息voidprint(student*std,intn){inti;for(i=0;istd[L].score[0]+std[L].score[1]+std[L].score[2])47 C++程序设计习题解答(王挺)L=j;}tmp=std[i];std[i]=std[L];std[L]=tmp;}}//按姓名搜索intsearch(student*std,intn,char*name){inti;for(i=0;iusingnamespacestd;typedefstruct_tagNode{intdata;_tagNode*next;}NODE,*PNODE;voidmain(){PNODEhead,tmp,cur,prev;head=newNODE;intn;cin>>n;head->data=n;head->next=0;cin>>n;while(n!=-1){tmp=newNODE;tmp->data=n;tmp->next=0;if(tmp->datadata){tmp->next=head;head=tmp;}else{prev=head;cur=prev->next;while(cur!=0&&tmp->data>cur->data){prev=cur;cur=cur->next;}tmp->next=cur;prev->next=tmp;}cin>>n;}cur=head;while(cur){cout<data<<"t";cur=cur->next;}}Chapter9/*P241T9.1编写一个程序,建立包含10个字符的链表,再建立一个新链表,包含一个链表的反序副本*/#includeusingnamespacestd;structNODE{charch;NODE*next;};47 C++程序设计习题解答(王挺)NODE*CreateList(char*str)//创建链表{NODE*head,*cur,*tmp;if(*str){head=newNODE;head->ch=*str;head->next=0;cur=head;}elsereturn0;for(str++;*str;str++){tmp=newNODE;tmp->ch=*str;tmp->next=0;cur->next=tmp;cur=tmp;}returnhead;}voidprintNode(NODE*head)//输出链表{while(head!=0){cout<ch<<"t";head=head->next;}cout<next;deletecur;cur=head;}}NODE*reverseLink(NODE*head){NODE*newhead,*tmp;if(head){newhead=newNODE;newhead->ch=head->ch;newhead->next=0;}while(head=head->next){tmp=newNODE;tmp->ch=head->ch;tmp->next=0;tmp->next=newhead;newhead=tmp;}returnnewhead;}voidmain(){charstr[]="ABCDEFGHIJK";NODE*head=CreateList(str);printNode(head);NODE*newhead=reverseLink(head);printNode(newhead);distroyLink(head);distroyLink(newhead);}/*P241T9.2编写一个程序,将两个字符链表连接起来,程序包含函数concatenate,该函数使用两个链表的引用作为函数参数,把第二个链表连接到第一个链表上。*/#includeusingnamespacestd;structNODE{charch;NODE*next;};NODE*CreateList(char*str)//创建链表{NODE*head,*cur,*tmp;if(*str){head=newNODE;head->ch=*str;head->next=0;cur=head;}elsereturn0;for(str++;*str;str++){tmp=newNODE;tmp->ch=*str;tmp->next=0;cur->next=tmp;cur=tmp;47 C++程序设计习题解答(王挺)}returnhead;}voidprintNode(NODE*head)//输出链表{while(head!=0){cout<ch<<"t";head=head->next;}cout<next;deletecur;cur=head;}}voidconcatenate(NODE*&head1,NODE*&head2)//将第二个链表head2连到head1后{NODE*prev=head1,*cur=head1->next;while(cur){prev=cur;cur=cur->next;}prev->next=head2;}voidmain(){charstr[]="ABCDEFGHIJK";NODE*head1=CreateList(str);NODE*head2=CreateList("LMNOPQRSTUVWXYZ");concatenate(head1,head2);printNode(head1);distroyLink(head1);}/*P241T9.3编写一个程序,将两个有序排列的整数链表合并成一个有序的整数链表,函数merge实现合并功能函数接受两个参数,这两个参数分别指向带合并的链表的头节点,函数返回一个指针,该指针指向合并后的链表的头节点*/#includeusingnamespacestd;structNODE{intch;NODE*next;};NODE*CreateList(int*a,intn)//创建有序链表{NODE*head,*cur,*tmp,*prev;head=newNODE;head->ch=*a;head->next=0;cur=head;for(a++,n--;n>0;a++,n--){tmp=newNODE;tmp->ch=*a;tmp->next=0;if(*ach){tmp->next=head;head=tmp;}else{prev=head;cur=prev->next;while(cur!=0&&tmp->ch>cur->ch){prev=cur;cur=prev->next;}tmp->next=cur;prev->next=tmp;}}returnhead;}NODE*merge(NODE*head1,NODE*head2){NODE*head=0,*cur;while(head1&&head2){if(head==0){if(head1->chch){47 C++程序设计习题解答(王挺)head=head1;head1=head1->next;}else{head=head2;head2=head2->next;}cur=head;}else{if(head1->chch){cur->next=head1;head1=head1->next;}else{cur->next=head2;head2=head2->next;}cur=cur->next;}}if(head1)cur->next=head1;elsecur->next=head2;returnhead;}voidprintNode(NODE*head)//输出链表{while(head!=0){cout<ch<<"t";head=head->next;}cout<next;deletecur;cur=head;}}voidmain(){inta[]={23,45,12,67,4,7,9,39,74,92};intb[]={45,67,23,57,18,29,54,72,97,12,56};NODE*head1=CreateList(a,sizeof(a)/sizeof(*a));NODE*head2=CreateList(b,sizeof(b)/sizeof(*b));NODE*newhead=merge(head1,head2);printNode(newhead);distroyLink(newhead);}/*P241T9.5建立一个链表,用一个函数将这个链表逆转,即将原来的表头变成表尾,原来的表尾变成表头*/#includeusingnamespacestd;structNODE{intch;NODE*next;};NODE*CreateList(int*a,intn)//创建有序链表{NODE*head,*cur,*tmp,*prev;head=newNODE;head->ch=*a;head->next=0;cur=head;for(a++,n--;n>0;a++,n--){tmp=newNODE;tmp->ch=*a;tmp->next=0;if(*ach){tmp->next=head;head=tmp;}else{prev=head;cur=prev->next;while(cur!=0&&tmp->ch>cur->ch){prev=cur;cur=prev->next;}tmp->next=cur;47 C++程序设计习题解答(王挺)prev->next=tmp;}}returnhead;}NODE*merge(NODE*head1,NODE*head2){NODE*head=0,*cur;while(head1&&head2){if(head==0){if(head1->chch){head=head1;head1=head1->next;}else{head=head2;head2=head2->next;}cur=head;}else{if(head1->chch){cur->next=head1;head1=head1->next;}else{cur->next=head2;head2=head2->next;}cur=cur->next;}}if(head1)cur->next=head1;elsecur->next=head2;returnhead;}NODE*reverseLink(NODE*head){NODE*newhead=head,*next;head=head->next;newhead->next=0;while(head){next=head->next;head->next=newhead;newhead=head;head=next;}returnnewhead;}voidprintNode(NODE*head)//输出链表{while(head!=0){cout<ch<<"t";head=head->next;}cout<next;deletecur;cur=head;}}voidmain(){inta[]={23,45,12,67,4,7,9,39,74,92};intb[]={45,67,23,57,18,29,54,72,97,12,56};NODE*head1=CreateList(a,sizeof(a)/sizeof(*a));NODE*head2=CreateList(b,sizeof(b)/sizeof(*b));NODE*newhead=merge(head1,head2);printNode(newhead);newhead=reverseLink(newhead);printNode(newhead);distroyLink(newhead);}补充从键盘输入一序列的整数,以-1作为输入结束标记,用这些数建立一个链表,然后输出该链表*/#includeusingnamespacestd;structNODE{intdate;NODE*next;47 C++程序设计习题解答(王挺)};NODE*CreateList()//创建链表{NODE*head,*cur,*tmp;intn;cin>>n;if(n!=-1)head=newNODE;head->date=n;head->next=0;cur=head;cin>>n;while(n!=-1){tmp=newNODE;tmp->date=n;tmp->next=0;cur->next=tmp;cur=tmp;cin>>n;}returnhead;}voidprintNode(NODE*head)//输出链表{while(head!=0){cout<date<<"t";head=head->next;}cout<next;deletecur;cur=head;}}voidmain(){NODE*head=CreateList();printNode(head);distroyLink(head);}/*Chapter11p288T11.2*/#include#include#includeusingnamespacestd;classTime{private:intyear,month,day;inthour,minute,second;public:Time(){structtm*newtime;time_taclock;time(&aclock);//Gettimeinsecondsnewtime=localtime(&aclock);year=newtime->tm_year;month=newtime->tm_mon;day=newtime->tm_mday;hour=newtime->tm_hour;minute=newtime->tm_min;second=newtime->tm_sec;}voidDispTime(){cout<usingnamespacestd;classRational{private:intdenominator;47 C++程序设计习题解答(王挺)intnumerator;intgetGcd(inta,intb);public:Rational(){denominator=1;numerator=0;}Rational(inta,intb);voidPrintRational();voidPrintRational2();Rational&RationalAdd(Rational&a);};Rational::Rational(inta,intb){if(a==0){cout<<"denominatorzero"<getGcd(a,b);this->denominator=a/t;this->numerator=b/t;}voidRational::PrintRational(){cout<getGcd(m,n);this->denominator=m/t;this->numerator=n/t;return*this;}voidRational::PrintRational2(){cout<<(double(numerator)/denominator)<usingnamespacestd;structStack{int*data;intmemNum;//栈顶指针intsize;};intinitStack(Stack&s,intsize){s.data=newint[size];if(s.data==NULL)return0;s.memNum=0;s.size=size;return1;}voidDistroyStatck(Stack&s){delete[]s.data;}intpop(Stack&s,int&num){if(s.memNum==0)return0;num=s.data[--s.memNum];return1;}intpush(Stack&s,intnum){if(s.memNum==s.size)return0;s.data[s.memNum++]=num;return1;}voidmain(){47 C++程序设计习题解答(王挺)inti,num;Stackstack;::initStack(stack,10);//入栈for(i=0;i<10;i++){cout<usingnamespacestd;voidmain(){inti,num;Stackstack(10);//pushfor(i=0;i<11;i++){if(!stack.push(i))cout<TreeNode::TreeNode(TDataTypenewdata){data=newdata;lchild=rchild=NULL;}intTreeNode::getData(){returndata;}voidTreeNode::setData(TDataTypenewdata){data=newdata;}TreeNode*TreeNode::getlchild(){returnlchild;}TreeNode*TreeNode::getrchild(){returnrchild;}voidTreeNode::insertNode(TDataTypenewdata){if(newdata>=data){if(rchild==NULL)rchild=newTreeNode(newdata);elserchild->insertNode(newdata);}else{if(lchild==NULL)lchild=newTreeNode(newdata);elselchild->insertNode(newdata);}}//BinaryTree.h#include"TreeNode.h"classBinaryTree{private:TreeNode*root;public:BinaryTree(TDataTyperoodata);voidinsertToTree(TDataTypenewdata);voidpreOrder(TreeNode*treeroot);TreeNode*getRoot();voidinOrder(TreeNode*treeroot);boolsearchData(TDataTypekey);boolsearchData(TreeNode*treeroot,TDataTypekey);};//BinaryTree.cpp#include"binarytree.h"#includeusingnamespacestd;BinaryTree::BinaryTree(TDataTyperootdata){root=newTreeNode(rootdata);}voidBinaryTree::insertToTree(TDataTypenewdata){root->insertNode(newdata);}voidBinaryTree::preOrder(TreeNode*treeroot){if(treeroot!=NULL){cout<getData()<<"";preOrder(treeroot->getlchild());preOrder(treeroot->getrchild());}}voidBinaryTree::inOrder(TreeNode*treeroot){if(treeroot!=NULL){47 C++程序设计习题解答(王挺)inOrder(treeroot->getlchild());cout<getData()<<"";inOrder(treeroot->getrchild());}}boolBinaryTree::searchData(TDataTypekey){returnsearchData(root,key);}boolBinaryTree::searchData(TreeNode*treeroot,TDataTypekey){if(treeroot!=NULL){if(key==treeroot->getData())returntrue;elseif(key>treeroot->getData())returnsearchData(treeroot->getrchild(),key);elsereturnsearchData(treeroot->getlchild(),key);}returnfalse;}TreeNode*BinaryTree::getRoot(){returnroot;}//TestBinary.cpp#include"binarytree.h"#includeusingnamespacestd;voidmain(){intdata[]={49,45,80,11,18,106,55,251,91};BinaryTreebt(data[0]);for(inti=1;iusingnamespacestd;classComplex{friendComplex&Add(Complex&c1,Complex&c2);private:intreal,img;public:Complex(intr=0,inti=0){real=r;img=i;}voidprintComplex(){cout<usingnamespacestd;#defineSIZE100//#defineDEBUGclassSet{friendvoidAddElement(Set&s,inte);friendvoidDelElement(Set&s,inte);friendSet&MergeSet(Set&s1,Set&s2);friendSet&Intersection(Set&s1,Set&s2);friendintInSet(Set&s,inte);private:inta[100];47 C++程序设计习题解答(王挺)intsize;public:Set();Set(int*a,intn);Set(Set&s);voidprintSet();};voidSet::printSet(){for(inti=0;ia[i]=s.a[i];this->size=s.size;}Set::Set(){size=0;}intInSet(Set&s,inte){inti;for(i=0;iusingnamespacestd;#definePI3.1415926classColumn{//增加友员函数:friendvoidSetColumn(Column&c,doublex,doubley,doubler,doubleh);friendvoidPrintColumn(Column&c);public:Column(doublex,doubley,doubler,doubleh);~Column(){};doublearea();doublevolumn();private:doubleheight;doubleradius;doublex,y;};Column::Column(doublex,doubley,doubler,doubleh){height=h;radius=r;this->x=x;this->y=y;}doubleColumn::area(){return2*PI*radius*height+PI*radius*radius*2;}doubleColumn::volumn(){returnPI*radius*radius*height;}voidSetColumn(Column&c,doublex,doubley,doubler,doubleh){c.height=h;c.radius=r;c.x=x;c.y=y;}voidPrintColumn(Column&c){cout<<"Column@("<usingnamespacestd;classTest{private:inta;doubleb;public:Test&seta(inti){a=i;return*this;}Test&setb(doubled){b=d;return*this;}intgeta(){returna;}doublegetb(){returnb;}Test&geta(int&i){i=a;return*this;}Test&getb(double&d){d=b;return*this;}};voidmain(){Testt;t.seta(2).setb(1.23);inta;47 C++程序设计习题解答(王挺)doubled;cout<usingnamespacestd;classCDate{friendostream&operator<<(ostream&output,CDate&date);private:intisleap();intyear,month,day;staticintdays[2][13];public:CDate(void){};CDate(inty,intm,intd);booloperator==(CDate&date);booloperator>(CDate&date);booloperator<(CDate&date);booloperator>=(CDate&date);intoperator-(CDate&date);CDate&operator++();CDate&operator--();CDate&operator+=(intd);CDate&operator-=(intd);};//filenameDate.cpp#include"Date.h"#includeusingnamespacestd;intCDate::days[][13]={{0,31,28,31,30,31,30,31,31,30,31,30,31},{0,31,29,31,30,31,30,31,31,30,31,30,31}};ostream&operator<<(ostream&output,CDate&date){output<CDate::days[isleap()][month]){day-=CDate::days[isleap()][month];month++;if(month>12){month=1;year++;}}return*this;}boolCDate::operator>(CDate&date){if(year>date.year)returntrue;elseif(yeardate.month)returntrue;elseif(monthdate.day)returntrue;elseif(daydate);}boolCDate::operator>=(CDate&date)47 C++程序设计习题解答(王挺){return*this>date||*this==date;}boolCDate::operator==(CDate&date){returnyear==date.year&&month==date.month&&day==date.day;}CDate&CDate::operator--(){day--;if(day<=0){month--;if(month<=0){month=12;year--;}day=CDate::days[isleap()][month];}return*this;}CDate::CDate(inty,intm,intd){year=y;month=m;day=d;}intCDate::isleap(){returnyear%4==0&&year%100||year%400==0;}CDate&CDate::operator+=(intd){for(inti=0;i=date){while(tmp>date){--tmp;d++;}}else{while(date>tmp){++tmp;d--;}}returnd;}CDate&CDate::operator-=(intd){for(inti=0;i#includeusingnamespacestd;staticchardaytable[2][13]={{0,31,28,31,30,31,30,31,31,30,31,30,31},{0,31,29,31,30,31,30,31,31,30,31,30,31}};classDate{47 C++程序设计习题解答(王挺)//重载为友元//friendDate&operator+(Date&date,intd);friendostream&operator<<(ostream&output,Date&d);public:Date();Date(inty,intm,intd);~Date();//重载为成员函数Date&operator+(intd);staticintisLeap(inty);protected:intyear,month,day;};Date::Date(){year=2008;month=1;day=1;}Date::Date(inty,intm,intd){year=y;month=m;day=d;}intDate::isLeap(inty){return(y%4==0&&y%100||y%400==0);}Date::~Date(){}Date&Date::operator+(intd){while(day+d>daytable[isLeap(year)][month]){d-=daytable[isLeap(year)][month]-day;if(month==12){year++;month=1;}elsemonth++;day=0;}day+=d;return*this;}ostream&operator<<(ostream&output,Date&d){output<daytable[Date::isLeap(date.year)][date.month]){d-=daytable[Date::isLeap(date.year)][date.month]-date.day;if(date.month==12){date.year++;date.month=1;}elsedate.month++;date.day=0;}date.day+=d;returndate;}*/voidmain(){Dated(2006,9,13);d=d+365;cout<usingnamespacestd;classComplex{friendostream&operator<<(ostream&os,Complex&complex);private:doublereal,imag;public:Complex(doubler=0.0,doublei=0);Complex&operator+(Complex&complex);47 C++程序设计习题解答(王挺)};//P334T1304//filename:complex.cpp#include"complex.h"Complex::Complex(doubler,doublei){real=r;imag=i;}Complex&Complex::operator+(Complex&complex){staticComplextmp;tmp.real+=complex.real;tmp.imag+=complex.imag;returntmp;}ostream&operator<<(ostream&os,Complex&complex){os<=0?"+":"")<#include"complex.h"usingnamespacestd;voidmain(){Complexa(1.23,2.34),b(2.0,4.5),c;c=a+b;cout<usingnamespacestd;classMyString{friendostream&operator<<(ostream&os,MyString&mystring);private:char*str;public:MyString(char*s="");MyString(MyString&mystr);~MyString();MyString&operator=(MyString&mystring);MyString&operator+(MyString&mystring);};//P335T1305filename:mystring.cpp#include#include"mystring.h"usingnamespacestd;MyString::MyString(char*s){str=newchar[strlen(s)+1];strcpy(str,s);}MyString::~MyString(){delete[]str;}MyString::MyString(MyString&mystr){str=newchar[strlen(mystr.str)+1];strcpy(str,mystr.str);}MyString&MyString::operator+(MyString&mystring){staticMyStringmystr("");charbuffer[1024]={""};strcpy(buffer,str);strcat(buffer,mystring.str);delete[]mystr.str;mystr.str=newchar[strlen(buffer)+1];strcpy(mystr.str,buffer);returnmystr;}MyString&MyString::operator=(MyString&mystring){if(&mystring!=this){delete[]str;str=newchar[strlen(mystring.str)+1];strcpy(str,mystring.str);}return*this;}ostream&operator<<(ostream&os,MyString&mystring){os<#include"mystring.h"usingnamespacestd;voidmain(){MyStrings1("Hello"),s2("C++World!");MyStrings=s1+s2;//必须重载=和拷贝构造函数cout<#include#includeusingnamespacestd;classTime{friendostream&operator<<(ostream&output,Time&time);friendistream&operator>>(istream&input,Time&time);public:Time(inth=0,intm=0,ints=0);private:inthour,minute,second;};Time::Time(inth,intm,ints){hour=(h>=0&&h<=23)?h:0;minute=(m>=0&&m<=59)?m:0;second=(s>=0&&s<=59)?s:0;}ostream&operator<<(ostream&output,Time&time){output<>(istream&input,Time&time){charbuffer[81];input.getline(buffer,3,"-");time.hour=atoi(buffer);input.getline(buffer,3,"-");time.minute=atoi(buffer);input.getline(buffer,3,"n");time.second=atoi(buffer);returninput;}voidmain(){Timetime(12,36,25);cin>>time;cout<#include#include#includeusingnamespacestd;classArray{friendostream&operator<<(ostream&output,Array&array);public:Array(intn);Array();~Array();int&operator[](intn);Array&operator=(Array&obj);intoperator==(Array&obj);private:intsize;int*ptr;};Array::Array(){ptr=0;size=0;}Array::Array(intn){ptr=newint[n];assert(ptr);size=n;memset((void*)ptr,0,n);//cleartozero}Array::~Array()47 C++程序设计习题解答(王挺){delete[]ptr;}int&Array::operator[](intn){assert(n<=size);returnptr[n];}Array&Array::operator=(Array&obj){if(&obj!=this){delete[]ptr;ptr=newint[obj.size];assert(ptr);size=obj.size;memcpy((void*)ptr,(void*)(obj.ptr),size*sizeof(int)/sizeof(char));}return*this;}intArray::operator==(Array&obj){if(size!=obj.size)return0;//大小不相等,肯定不相等for(inti=0;i#includeusingnamespacestd;classHugeInt{friendostream&operator<<(ostream&output,HugeInt&hugeint);public:HugeInt(HugeInt&hugeint);HugeInt(longval=0);HugeInt(constchar*string);HugeIntoperator+(HugeInt&hugeint);HugeInt&operator++();HugeIntoperator++(int);private:shortinteger[30];};ostream&operator<<(ostream&output,HugeInt&hugeint){inti;for(i=29;i>=0&&hugeint.integer[i]==0;i--);if(i<=0)output<<0<=0;i--)output<=0;i--){integer[strlen(string)-1-i]=string[i]-"0";}}HugeInt&HugeInt::operator++(){shortcarry=0,a;for(inti=0;i<30;i++){47 C++程序设计习题解答(王挺)a=integer[i]+1+carry;carry=a/10;integer[i]=a%10;if(!carry)break;}return*this;}HugeIntHugeInt::operator++(int){HugeInttemp(*this);++(*this);returntemp;}HugeInt::HugeInt(longval){memset((void*)integer,0,sizeof(short)*30);inti=0;while(val&&i<=29){integer[i++]=short(val%10);val/=10;}}HugeIntHugeInt::operator+(HugeInt&hugeint){HugeInttemp;shorta;intcarry=0;for(inti=0;i<30;i++){a=integer[i]+hugeint.integer[i]+carry;temp.integer[i]=a%10;carry=a/10;}returntemp;}voidmain(){HugeInthugeint1("1234567804"),hugeint2(876543210L);cout<usingnamespacestd;classMyString{friendostream&operator<<(ostream&output,MyString&mystr);private:char*str;public:MyString(constchar*s="");//类型转换构造函数MyString(constinti);//类型转换构造函数MyString(constdoubled);//类型转换构造函数~MyString();operatordouble()const;//类型转换运算符函数operatorlong()const;//类型转换运算符函数};//P336T1309//filename:mystring.cpp#include"mystring.h"#include#includeMyString::MyString(constchar*s){str=newchar[strlen(s)+1];assert(str);strcpy(str,s);}MyString::~MyString(){delete[]str;}MyString::MyString(constinti){charbuffer[33];_itoa(i,buffer,10);str=newchar[strlen(buffer)+1];assert(str);strcpy(str,buffer);}MyString::MyString(constdoubled){charbuffer[64];//aslargeasposibble_gcvt(d,32,buffer);str=newchar[strlen(buffer)+1];assert(str);strcpy(str,buffer);}47 C++程序设计习题解答(王挺)/**/MyString::operatordouble()const{char*endptr;returnstrtod(str,&endptr);}MyString::operatorlong()const{char*endptr;returnstrtol(str,&endptr,10);}ostream&operator<<(ostream&output,MyString&mystr){output<usingnamespacestd;voidmain(){inta[]={1,2,3,4,5};intb[]={5,4,3,2,1};Vectorv1(a,sizeof(a)/sizeof(int));Vectorv2(b,sizeof(b)/sizeof(int));cout<#include"matrix.h"#ifndef__VECTOR__#define__VECTOR__classVector{friendstd::ostream&operator<<(std::ostream&out,Vector&v);friendVectoroperator*(Vector&v,Matrix&m);//向量和矩阵相乘,结果为一向量private:int*elem;//向量存储空间,动态分配intsize;//向量中元素的个数public:Vector();Vector(intsize);//构造一个空的向量Vector(inta[],intsize);Vector(Vector&v);//47 C++程序设计习题解答(王挺)在类中如果有成员函数返回临时对象,必须重载拷贝构造函数~Vector();Vectoroperator+(Vector&v);//两个向量相加,生成一个临时向量Vectoroperator*(Vector&v);//两个向量相乘,生成一个临时向量Vector&operator=(Vector&v);//如果动态分配空间,必须重载赋值操作Vectoroperator*(inti);//向量的数乘运算int&operator[](inti);//能在程序中使用v[i]操作向量的的元素inlineintSize()const{returnsize;}inlineint*Elem()const{returnelem;}};#endif//__VECTOR__//vector.cpp#include"vector.h"#include#includeusingnamespacestd;//构造函数Vector::Vector(){elem=newint[0];size=0;}//构造函数Vector::Vector(inta[],intsize){this->size=size;elem=newint[size];for(inti=0;isize=size;elem=newint[size];memset(elem,0,size*sizeof(int));//清零}//析构函数Vector::~Vector(){delete[]elem;}VectorVector::operator+(Vector&v){assert(size==v.size);Vectortmp;tmp.size=size;tmp.elem=newint[size];for(inti=0;i#ifndef__MATRIX__#define__MATRIX__classMatrix{friendstd::ostream&operator<<(std::ostream&out,Matrix&m);private:int*elem;introw;intcol;public:Matrix();Matrix(int*a,intr,intc);~Matrix();Matrix(Matrix&m);//拷贝构造函数Matrixoperator+(Matrix&m);//矩阵相加Matrixoperator*(Matrix&m);//矩阵相乘Matrix&operator=(Matrix&m);//矩阵赋值Matrixoperator*(int);//矩阵数乘MatrixTranspose();//矩阵转置inlineintRow()const{returnrow;}inlineintCol()const{returncol;}inlineint*Elem()const{returnelem;}};#endif//__MATRIX__//Matrix.cpp#include"matrix.h"#include#includeusingnamespacestd;//构造函数Matrix::Matrix(){elem=newint[0];row=0;col=0;}//构造函数Matrix::Matrix(int*a,intr,intc){row=r;col=c;elem=newint[r*c];inti;for(i=0;i#include"circle.h"#include"rectangle.h"usingnamespacestd;voidmain(){Circlec;c.show();Rectangler;r.show();}//filenameshape.h#ifndef__SHAPE#define__SHAPEclassShape{public:doublearea();doublegirth();voidshow();};#endif//filenameshape.cpp#include#include"shape.h"usingnamespacestd;doubleShape::area(){return0;}doubleShape::girth(){return0.0;}voidShape::show(){cout<<"ShapeObject:"<#include"circle.h"usingnamespacestd;Circle::Circle(intx,inty,doubleradius){this->x=x;this->y=y;this->radius=radius;}doubleCircle::area(){return3.14*radius*radius;}voidCircle::show(){Shape::show();cout<<"Circle@("<#include#include"triangle.h"usingnamespacestd;//类的实现请同学们完成Chapter16P422T1602#include#includeusingnamespacestd;//如何改进??voidmain(){ofstreamoutFile("c:\mytest.txt");charch;while(cin>>ch){outFile<#includeusingnamespacestd;voidUsage(){cout<<"mycopy.exeSourceFileNameDestinationFileName"<>ch)outFile.put(ch);inFile.close();outFile.close();}P423T1605#include#includeusingnamespacestd;classTriangle{friendostream&operator<<(ostream&output,Triangle&tri);private:doublex,y,z;public:Triangle(){}Triangle(doublea,doubleb,doublec){x=a;y=b;z=c;}voidsaveToFile(ostream&outFile);boolloadFromFile(istream&inFile);};ostream&operator<<(ostream&output,Triangle&tri){output<#includeusingnamespacestd;classTriangle{friendostream&operator<<(ostream&output,Triangle&tri);friendistream&operator>>(istream&input,Triangle&tri);private:doublex,y,z;public:Triangle(){}Triangle(doublea,doubleb,doublec){x=a;y=b;z=c;}voidsaveToFile(ostream&outFile);boolloadFromFile(istream&inFile);};47 C++程序设计习题解答(王挺)ostream&operator<<(ostream&output,Triangle&tri){tri.saveToFile(output);returnoutput;}istream&operator>>(istream&input,Triangle&tri){tri.loadFromFile(input);returninput;}boolTriangle::loadFromFile(istream&inFile){if(inFile.peek()!=EOF){inFile>>x>>y>>z;returntrue;}elsereturnfalse;}voidTriangle::saveToFile(ostream&outFile){outFile<>t){cout<usingnamespacestd;classA{};voidmain(){inta;cout<<"Enteraninteger:"<>a){try{switch(a%7){case0:char*pc;throwpc;case1:int*pi;throwpi;case2:double*pd;throwpd;case3:float*pf;throwpf;case4:void*pv;throwpv;case5:long*pl;throwpl;case6:A*pa;throwpa;}}catch(char*e){cout<<"char*Exception"<usingnamespacestd;classA{};voidterminate_fun(){cout<<"unexceptedExceptionoccured"<usingnamespacestd;classIndexOutOfRange{private:char*message;public:IndexOutOfRange(){message="Indexoutofrange";}IndexOutOfRange(char*msg){message=msg;}virtual~IndexOutOfRange(){}char*Message()const{returnmessage;}};voidmain(){inta[5];inti;cout<<"Enteraninteger:"<>i;try{if(i<0||i>=5)throwIndexOutOfRange();//输入的数不合理,抛出异常elsea[i]=i;}catch(IndexOutOfRangee){cout<usingnamespacestd;classA{};voidterminate_fun(){cout<<"unexceptedExceptionoccured"<#includeusingnamespacestd;templateboolFindInArray(_Elema[],intaLength,_Eleme){for(inti=0;iusingnamespacestd;//递归实现templatevoidReverse(_Elema[],intaLength){_Eleme;if(aLength>1){e=*a;*a=a[aLength-1];a[aLength-1]=e;Reverse(a+1,aLength-2);}}templatevoidPrintArray(_Elema[],intaLength){for(inti=0;i#includeusingnamespacestd;#defineMAX_SIZE100templateclassArray{friendostream&operator<<<_Elem>(ostream&output,constArray<_Elem>&a);private:_Elem*elem;size_tsize;size_tmax_size;public:Array()throw();Array(_Elema[],size_tn)throw();~Array();47 C++程序设计习题解答(王挺)_Elem&operator[](intindex)throw();//根据下标取元素的值,根据下标设置数组元素voidInsertAt(intindex,_Eleme);//在指定的位置插入一个数组元素voidAdd(_Eleme);//在数组尾部添加一个元素};templateostream&operator<<(ostream&output,constArray<_Elem>&a){for(size_ti=0;iArray<_Elem>::Array(){max_size=MAX_SIZE;elem=new_Elem[max_size];size=0;}templateArray<_Elem>::Array(_Elem*a,size_tn){size=n;max_size=size;elem=new_Elem[max_size];memcpy(elem,a,size*sizeof(_Elem));}template_Elem&Array<_Elem>::operator[](intindex){assert(index>=0&&index<(int)size);returnelem[index];}templatevoidArray<_Elem>::InsertAt(intindex,_Eleme){assert(index>=0&&index<=(int)size);if(max_size==size)//空间不足,需要加大空间{max_size*=2;size+=1;_Elem*tmp=new_Elem[max_size];assert(tmp);memcpy(tmp,elem,size*sizeof(_Elem));delete[]elem;elem=tmp;}inti;for(i=(int)size;i>index;i--)elem[i]=elem[i-1];elem[i]=e;}templatevoidArray<_Elem>::Add(_Eleme){InsertAt(size,e);}templateArray<_Elem>::~Array(){delete[]elem;}voidmain(intargc,char**argv){inta[]={1,2,3,4,5,6,9,0};Arrayb(a,sizeof(a)/sizeof(*a));b[2]=10;cout<a.lengthcout<c(d,sizeof(d)/sizeof(*d));c[2]=10;cout<a.lengthcout<