C++面向对象程序设计双语教程(第3版)-参考答案 刘嘉敏 【ch08】 Templates_第1页
C++面向对象程序设计双语教程(第3版)-参考答案 刘嘉敏 【ch08】 Templates_第2页
C++面向对象程序设计双语教程(第3版)-参考答案 刘嘉敏 【ch08】 Templates_第3页
C++面向对象程序设计双语教程(第3版)-参考答案 刘嘉敏 【ch08】 Templates_第4页
C++面向对象程序设计双语教程(第3版)-参考答案 刘嘉敏 【ch08】 Templates_第5页
已阅读5页,还剩4页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

Chapter8Templates1.Findtheerror(s)ineachofthefollowinglinesandexplainhowtocorrectit.略。2.DefineaSwapfunctiontemplatethatimplementsexchangeoftwonumbers.Implementthetemplatebyusingtypesintanddouble.为了实现两个数字的交换函数模板,我们可以使用模板代码来处理不同数据类型。```cpptemplate<typenameT>voidswapTwoNumbers(T&a,T&b){Ttemp=a;a=b;b=temp;}```这个交换函数模板可以处理任何数据类型,包括`int`和`double`。```cppintmain(){inta=5;intb=10;swapTwoNumbers(a,b);cout<<\Swappedvalues:\<<a<<\\<<b<<endl;doublex=2.5;doubley=4.7;swapTwoNumbers(x,y);cout<<\Swappedvalues:\<<x<<\\<<y<<endl;return0;}```运行上述示例代码,输出会是:```Swappedvalues:105Swappedvalues:4.72.5```3.DefineagetMaxfunctiontemplatewithfindingthemaximumvalueamong10numbers.Implementitbyusingtypesintandfoat.当使用int类型时,可以使用以下模板来实现getMax函数:```cpptemplate<typenameT>TgetMax(Tvalues[],intsize){TmaxVal=values[0];for(inti=1;i<size;i++){if(values[i]>maxVal){maxVal=values[i];}}returnmaxVal;}intmain(){intintArr[]={1,6,2,8,5,3,9,4,7,0};intintMax=getMax<int>(intArr,10);cout<<\ThemaximumvalueinintArris:\<<intMax<<endl;floatfloatArr[]={1.5,6.7,2.3,8.1,5.9,3.4,9.8,4.2,7.6,0.9};floatfloatMax=getMax<float>(floatArr,10);cout<<\ThemaximumvalueinfloatArris:\<<floatMax<<endl;return0;}```这个模板函数可以适用于不同类型的数组,并返回该数组中的最大值。在main函数中,我们分别传入了一个int类型和一个float类型的数组,并打印出了它们的最大值。4.Writeafunctiontemplatetocomparethevaluesoftwovalues.Iftheyareequal,retur1;otherwise,return0.Instantiateitbyusingtypesdoubleandstring.以下是一个函数模板的示例,可以用来比较两个值的值,并返回相应的结果:```cpptemplate<typenameT>intcompareValues(Ta,Tb){if(a==b){return1;}else{return0;}}//实例化模板函数,传入双精度类型的值doubledoubleValue1=3.14;doubledoubleValue2=3.14159;intresult1=compareValues<double>(doubleValue1,doubleValue2);//result1的值为0,因为doubleValue1和doubleValue2不相等//实例化模板函数,传入字符串类型的值stringstringValue1=\Hello\stringstringValue2=\World\intresult2=compareValues<string>(stringValue1,stringValue2);//result2的值为0,因为stringValue1和stringValue2不相等```通过将模板函数的T替换为具体的类型(例如双倍类型和字符串类型),我们可以实例化函数并进行比较。在示例中,当传入两个不相等的值时,函数返回值为0。5.Defineaclasstemplatearraythatproducesaboundscheckedarray.Instantiateitbyusingtypesintandfloat.以下是使用类模板实现的边界检查数组:```cpp#include<iostream>usingnamespacestd;template<typenameT>classBoundArray{private:T*arr;intsize;public:BoundArray(intn){arr=newT[n];size=n;}~BoundArray(){delete[]arr;}T&operator[](intindex){if(index<0||index>=size){cout<<\索引超出范围!\<<endl;throwout_of_range(\索引超出范围\}returnarr[index];}};intmain(){try{BoundArray<int>intArr(5);for(inti=0;i<5;i++){intArr[i]=i;}for(inti=0;i<6;i++){cout<<intArr[i]<<\\}cout<<endl;}catch(constexception&e){cout<<\捕获到异常:\<<e.what()<<endl;}try{BoundArray<double>doubleArr(3);for(inti=0;i<3;i++){doubleArr[i]=i+0.5;}for(inti=0;i<4;i++){cout<<doubleArr[i]<<\\}cout<<endl;}catch(constexception&e){cout<<\捕获到异常:\<<e.what()<<endl;}return0;}```这个类模板`BoundArray`接受一个类型参数`T`,其中`T`可以是`int`或者`float`等类型。在类的内部,我们用一个动态分配的数组`arr`来存储数据,并使用私有成员变量`size`来记录数组的大小。`BoundArray`中的`operator[]`重载函数会对索引进行边界检查,如果索引小于0或者大于等于数组大小,则会抛出`out_of_range`异常并输出错误消息。在`main`函数中,我们使用`BoundArray`类模板实例化了一个整型数组`intArr`和一个浮点型数组`doubleArr`,并演示了数组的访问和边界检查。此程序的输出应该是:```01234捕获到异常:索引超出范围```这表明整型数组的大小为5,而浮点型数组的大小为3。由于整型数组访问了索引为5的元素(超出了范围),所以触发了边界检查并抛出了异常。而浮点型数组则直接在访问索引为4的元素时触发了边界检查,也抛出了异常。6.DefineaStackclasstemplate.Implementthetemplatebyusingintandchar.```cpptemplate<typenameT>classStack{private:staticconstintmax_size=100;Tdata[max_size];inttop_index;public:Stack(){top_index=-1;}boolisEmpty(){returntop_index==-1;}boolisFull(){returntop_index==max_size-1;}voidpush(Tvalue){if(isFull()){std::cout<<\Stackoverflow!\<<std::endl;return;}data[++top_index]=value;}Tpop(){if(isEmpty()){std::cout<<\Stackunderflow!\<<std::endl;returnT();}returndata[top_index--];}Ttop(){if(isEmpty()){std::cout<<\Stackisempty!\<<std::endl;returnT();}returndata[top_index];}};```这个类模板中有一个静态成员变量`max_size`用于定义栈的最大容量,一个数组`data`存储数据,以及一个`top_index`表示栈顶的索引。类模板提供了一些基本的堆栈操作,包括`push`入栈、`pop`出栈、`top`查看栈顶元素、`isEmpty`判断栈是否为空、`isFull`判断栈是否已满。在使用这个类模板时,你可以用`Stack<int>`来创建一个整型堆栈,者用`Stack<char>`来创建一个字符型堆栈。例如:```cppStack<int>intStack;intStack.push(5);intStack.push(10);intStack.push(15);std::cout<<intStack.pop()<<std::endl;//输出15std::cout<<intStack.top()<<std::endl;//输出10Stack<char>charStack;charStack.push('a');charStack.push('b');std::cout<<charStack.pop()<<std::endl;//输出bstd::cout<<charStack.top()<<std::endl;//输出a```7.Giventhefollowingprogram:WriteoutthedefinitionoftheVectorclasstemplate.略。8.Writeaclasstemplatetosearchanelementinanorderedarraybyusingdichotomy.```cpp#include<iostream>#include<vector>template<typenameT>classBinarySearch{public:intsearch(conststd::vector<T>&arr,constT&target){intleft=0;intright=arr.size()-1;while(left<=right){intmid=left+(right-left)/2;if(arr[mid]==target)returnmid;if(arr[mid]<target)left=mid+1;elseright=mid-1;}return-1;//返回-1表示未找到目标元素}};intmain(){std::vector<int>arr={1,3,5,7,9,11,13,15};BinarySearch<int>bs;inttarget=7;int=bs.search(arr,target);if(index!=-1

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论