简答题 C++
题号 #2607298

请使用VC6或使用【答题】菜单打开考生文件夹proj3下的工程proj3,其中包含了类IntegerSet和主函数main的定义。一个IntegerSet对象就是一个整数的集合,其中包含0个或多个无重复的整数;为了便于进行集合操作,这些整数按升序存放在成员数组elem的前若干单元中。成员函数add的作用是将一个元素添加到集合中(如果集合中不存在该元素),成员函数remove从集合中删除指定的元素(如果集合中存在该元素)。请编写成员函数remove。在main函数中给出了一组测试数据,此时程序的正确输出结果应为:
2  3 4 5  27 28  31  66 75
2 3 4 5  6 27 28 31 56 75
2 3 4 5  6  19 27 28 31  66 75
3 4 5 6  19 27 28 31  66 75
3 4 5 6  19 27 28 31  66 75
要求:
补充编制的内容写在“//***********333***********”与“//***********666***********”之间,不得修改程序的其他部分。
注意:程序最后将结果输出到文件out.dat中。输出函数writeToFile已经编译为obj文件,并且在本程序中调用。
//IntegorSet.h
#ifndef INTEGERSET
#define INTEGERSET
#include<iostream>
using namespace std;
const int MAXELEMENTS=100;
//集合最多可拥有的元素个数
class IntegerSet{
int elem[MAXELEMENTS];
//用于存放集合元素的数组
int counter;  //用于记录集合中元素个数的计数器
puhlic:
IntegerSet():counter(0){}
//创建一个空集合
IntegerSet(int data[],int size);
//利用数组提供的数据创建一个整数集合
void add(int element);
//添加一个元素到集合中
void remeve(int element);
//删除集合中指定的元素
int getCount()const{return counter;}
//返回集合中元素的个数
int getElement(int i)const{retum elem[i];}//返回集合中指定的元素
void show()const;
};
void WriteToFile(char*);
#endif
//main.cpp
#include”IntegerSet.h”
#include<inmanip>
IntegerSet::IntegerSet(int data[],int size):counter(0){
for(int i=0;i<size;i++)
add(data[i]);
}
}
void IntegerSet::add(int element){
int j;
//从后往前寻找第一个小于等于element的元素
for(j=counter;j>0;j-)
if(element>=elem[j一1])break;
//如果找到的是等于element的元素,说明要添加的元素已经存在,直接返回
if(j>0)
if(element==elem[j-1])return;
//如果找到的是小于element的元素,j就是要添加的位置
//该元素及其后面的元素依次后移,腾出插入位置
for(int k=counter;k>j;k一)
elem[k]=elem[k一1];
elem[j]=element;//将element插入到该位置
counter++;    //计数器加l
}
void IntegerSet::remove(int element){
//***************333***************
//***************666***************
void IntegerSet::show()const{
for(int i=0;i<getCount();i++)
cout<<setw(4)<<getElement(i);
cout<<endl:
}
int main(){
int d[]={5,28,2,4,5,3,2,75,27,66,31};
IntegerSet S(d,11);S.show();
S.add(6);    s.show();
S.add(19);    S.show();
S.remove(2);  s.show();
S.add(4);    S.show();
writeToFile(””);
return 0;
}

进入在线模考

参考答案

暂无

答案解析

for(int i=0:i<counter;i++)
//遍历整个集合(数组elem)
if(element==elem[i])
//女il果element等于elem[i]
{
for(intj=i;j<counter-1;j++)
//从i开始遍历集合elem
etem[j]=elem[j+1];
//把elemi i+1]赋值给elem[j]
counter--;//elem长度自减
re|urn;//返吲

你可能感兴趣的试题

A.算法就是程序
B.设计算法时只需要考虑数据结构的设计
C.设计算法时只需要考虑结果的可靠性
D.以上三种说法都不对
A.有一个以上根结点的数据结构不一定是非线性结构
B.只有一个根结点的数据结构不一定是线性结构
C.循环链表是非线性结构
D.双向链表是非线性结构
A.叶子结点总是比度为2的结点少一个
B.叶子结点总是比度为2的结点多一个
C.叶子结点数是度为2的结点数的两倍
D.度为2的结点数是度为1的结点数的两倍
找试题 · 找答案 · 找资料 在线模考