问答题
请使用VC6或使用【答题】菜单打开
proj3下的工程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 main()
{
int a[] = {1,2,3,5,8,10};
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;
}
【正确答案】
【答案解析】for (int i = 0; i <= set.GetEnd(); i++) //遍对象set数组
if (IsMemberOf (set.GetElement (i))) //判断对象Set数组第i个值是不是集合中的值,如果是则把它插入到a中
a [size ++] = set.GetElement(i);
答案考生文件夹
[考点] 本题考查的是IntSet类,其中涉及构造函数、bool函数和成员函数。本类是一个用于表示正整数集合的类,题目要求填写的函数能实现交集的功能,也就是将两个数组内的元素进行比较,将一样的元素提取出来。
[解析] 主要考查考生对数组的掌握,根据IntSet类的构造函数:
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];
}
可知数组element用来装载集合,end表示数组长度,因此调用函数IsMemberOf来判断set中的元素是否存在于集合中,如果存在则放入数组a中。
主要考查考生对数组的掌握,集合可以用数组来实现,交集就是将两个数组中相等的元素提取出来放入一个新建立的数组。