应用题 3.请打开考生文件夹下的解决方案文件proj3,其中声明IntSet是一个用于表示正整数集合的类。IntSet的成员函数Intersection的功能是求当前集合与另一个集合的交集。请完成成员函数Intersection。在main函数中给出了一组测试数据,此时程序的输出应该是:
求交集前:
1 2 3 5 8 10
2 8 9 11 30 56 67

求交集后:
1 2 3 5 8 10
2 8 9 11 30 56 67
2 8
要求:
补充编制的内容写在“//********333********”与“//********666********”之间,不得修改程序的其他部分。
注意:程序最后将结果输出到文件out.dat中。输出函数writeToFile已经编译为obj文件,并且在本程序中调用。
//Intset.h
#include<iostream>
using namespace std;

const int Max=100;
class IntSet
{
public:
IntSet()
//构造一个空集合
{
end=一1;
}
IntSet(int a[],int size)//构造一个包含数组a中size个元素的集合
{
if(size>=Max)
end=Max一1;
else
end=size一1;
for(int i=0;i<=end;i++)
element[i]=a[i];
}
bool IsMemberOf(int a)
//判断a是否为集合中的一个元素
{
for(int i=0;i<=end;i++)
if(element[i]==a)
return true;
return false;
}
int GetEnd(){return end;}
//返回最后一个元素的下标
int GetElement(int i){return element[i];}
//返回下标为i的元素
IntSet Intersection(IntSet&set);
//求当前集合与集合set的交
void Print()
//输出集合中的所有元素
{
for(int i=0; i<=end;i++)
if((i+1)%20==0)
cout<<element[i]<<endl;
else
cout<<element[i]<<' ';
cout<<endl;
}
private:
int element[Max];
int end;
};
void writeToFile(const char *);
//main.cpp
#include"IntSet.h"
IntSet IntSet:: Intersection(IntSet& set)
{
int a[Max],size=0;
//********333********


//********666********
return IntSet(a,size);
}

int msin()
{
int a[]={1,2,3,5,8,1 0);
int b[]={2,8,9,11,30,56,67);
IntSet set1(a,6),Set2(b,7),set3;
cout<<"求交集前:"<<endl;
set1.Print();
set2.Print();
set3.Print();
set3=set1.Intersection(set2);
cout<<endl<<"求交集后:"<<endl;
set1.Print();
set2.Print();
set3.Print();
writeToFile("");
return 0;
}
【正确答案】1 for(Int 1 =0;1 <=set.GetEnd();i++) //遍对象set数组
2 if(IsMemberOf(set.GetElement(i))) //判断对象Set数组第i个值是不是集合中的值,如果是则把它插入到a中
3 a[size++] = set.GetElement(i);
【答案解析】主要考查考生对数组的掌握,根据IntSet类的构造函数:
IntSet(int a[],int size)
//构造一个包含数组a中size个元素的集合
1 {
2 if(size>=Max)
3 end=Max—1;
4 else
5 end=size一1;
6 for(int i=0; i<=end;i++)
7 element[i]=a[i];
8 }
可知数组element用来装载集合,end表示数组长度,因此调用函数IsMemberOf来判断set中的元素是否存在于集合中,如果存在则放入数组a中。