请使用“答题”菜单或使用VC6打开考生文件夹下的工程proj3,其中声明了List类,它是一个用于表示整数列表的类。List的成员函数insert的功能是将一个指定的整数插入到列表的指定位置处,原位置处的及其后的所有元素依次向后顺移一个位置。请补充完整成员

admin2021-09-05  36

问题 请使用“答题”菜单或使用VC6打开考生文件夹下的工程proj3,其中声明了List类,它是一个用于表示整数列表的类。List的成员函数insert的功能是将一个指定的整数插入到列表的指定位置处,原位置处的及其后的所有元素依次向后顺移一个位置。请补充完整成员函数insert。在main函数中给出了一组测试数据,此情况下程序的输出应该是:
53791326810
5371326810
5—23371326—19810
注意:只需在//**********333**********和//**********666**********之间填入所编写的若干语句,不要改动程序中的其他内容。
#include"List.h"
intmain(){
intdat[]={5,3,7,9,13,2,6,8,1,0);
List1ist(dat,10);
list.show();
list.remove(3);
list.show();
list.insert(一23,1);
list.insert(一19,7);
1ist.show();
writeToFile("C:\\test\\");
return0;
}
}/proj3\list.cpp
#inClude"LiSt.h"
List::List(intd[],intsize){
intmin=(MAX—SIZE>size?size:
MAX_SIZE);
for(inti=0;i=d
count=min;
}
voidList::insert(intdata,int
pos){
//存储空间已满,无法增添新元素
if(count>=MAX_SIZE)return;
//指定的插入位置在最后元素之后,紧贴最后元素之后插入新元素。
if(pos>=count){elem[count++]=data;return;}
//指定的插入位置未超过最后元素处,须移动有关元素以便腾空指定的插入位置,然后插入新元素。
//********333********
//********666********
}
voidList::remove(intpos){
if(pos<0||pos>=count)return;
for(inti=pos;ielem=elem[i+1];
count一一;
}
voidList::show(ostream&os)const{
for(inti=0;ielem<<’’;
OS<}
//proj3\list.h
{}1nclude<10Stream>
usingnamespacestd;
#defineMAX_SIZE100
classListt
intelem[MAXSIZE];//存放列表元素的数组
intcount;//列表中元素的个数
public:
List():count(0){}
List(intd[],intsize);
intsize()const{returncount;)
//将数据元素data插入到位置pos处。
注意第一个元素的位置是0。
voidinsert(intdata,intpos);
//删除位置pos处的数据元素。
voidremove(intpos);
//输出列表内容
voidshow(ostream&os=cout)
const;
};
voidwriteToFile(constchar*path);

选项

答案for(inti=count一1;i>=pos;i--) { elem[i+1]=elem[i]; } elem[pos]=data; count++;

解析 主要考查考生对对象处理的掌握,函数insert的功能是将一个指定的整数data插入到列表的指定位置pos处,原位置处的及其后的所有元素依次向后顺移一个位置。首先通过比较count与MAX_SIZE判断存储空间是否已满,若存储空间已满,直接返回;然后判断插入的位置是否在当前数组最后元素之后,若是,则紧贴最后元素之后插入新元素即可;最后使用for循环,将pos位置及其之后的所有元素向后顺移一位,再将data插入pos位置,同时更新count的值。
转载请注明原文地址:https://kaotiyun.com/show/365p777K
0

最新回复(0)