请打开考生文件夹下的解决方案文件proj3,其中包含主程序文件main.cpp和用户定义的头文件Array.h,整个程序包含有类Array的定义和主函数main的定义。请把主程序文件中的Array类的成员函数Contrary( )的定义补充完整,经补充后运行程序,得到的输出结果应该是:
5 8
5,4,3,2,1
0,0,8.4,5.6,4.5,3.4,2.3,1.2
注意:只允许在“//********333********”和“//********666********”之间填写内容,不允许修改其他任何地方的内容。
//Array.h
#include< iostream >
using namespace std;
template< class Type,int m >
class Array{//数组类
public:
Array(Typeb[ ],int mm){//构造函数
for(int i=0;i< m;i++)
if(i< mm)a[i]=b[i];
elsea[i]=0;
}
void Contrary( );
//交换数组a中前后位置对称的元素的值
int Length( )const{return m;}
//返回数组长度
Type operator[ ](int i)const{
//下标运算符重载为成员函数
if(i< 0||i >=m)
{cout< < "下标越界!"< < endl;exit(1);}
return a[i];
}
private:
Type a[m];
};
void writeToFile(const char*);
//不用考虑此语句的作用
//main.cpp
#include"Array.h"
//交换数组a中前后位置对称的元素的值
template< class Type,int m >
void Array< Type,m >::Contrary( ){//补充函数体
//********333********
//********666********
}
int main( ){
int s1[5]={1,2,3,4,5};
double s2[6]={1.2,2.3,3.4,4.5,5.6,8.4};
Array< int,5 >d1(s1,5);
Array< double,8 >d2(s2,6);
int i;
d1.Contrary( );d2.Contrary( );
cout< < d1.Length( )< < ' '< < d2.Length( )< < endl;
for(i=0;i< 4;i++)
cout< < d1[i]< < ",";
cout< < d1[4]< < endl;
for(i=0;i< 7;i++)
cout< < d2[i]< < ",";
cout< < d2[7]< < endl;
writeToFile(" ");
//不用考虑此语句的作用
return0;
}
【正确答案】for(int i=0,j=m-1;i< j;i++,j--)
{//i从0开始自加,j从数组最一位开始自减,条件是i< j,开始遍历数组a
Type temp=a[i];
//把a[i]赋值给变量temp
a[i]=a[j];//把a[j]赋值给[j]
a[i]=temp;
//把temp赋值给a[j],最终使a[i]与a[j]值的互换
}
【答案解析】主要考查考生对交换算法的掌握情况,根据题目对要完成的函数Contrary的要求:交换数组a中前后位置对称的元素的值。这里取下标j=0,即为数组中的第一个元素,j=m-1,即为数组中的最后一个元素,利用中间值temp交换元素的值,然后i逐次递增的同时j逐次递减,再交换,循环到i >j时停止交换即可。