应用题
1. 请使用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 66 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文件,并且在本程序中调用。
//IntegerSet. h
#ifndef INTEGERSET
#define INTEGERSET
#include<iostream>
using namespace std;
const int MAXELEMENTS=100;
//集合最多可拥有的元素个数
class IntegerSet {
int elem[MAXELEMENTS];
//用于存放集合元素的数组
int counter;//用于记录集合中元素个数的计数器
public:
IntegerSet(): counter(0) {}
//创建一个空集合
IntegerSet(int data[], int size);
//利用数组提供的数据创建一个整数集合
void add(int element);
//添加一个元素到集合中
void remove(int element);
//删除集合中指定的元素
int getCount()const {return counter;}
//返回集合中元素的个数
int getElement(int i)const {return elem[i];}//返回集合中指定的元素
void show()const;
};
void WriteToFile(char*);
#endif
//main. cpp
#include"IntegerSet. h"
#include<iomanip>
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++;//计数器加1
}
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;
}