问答题
请使用[答题]菜单命令或直接用VC6打开考生文件夹下的工程proj3,其中声明的IntSet是一个用于表示正整数集合的类。IntSet的成员函数IsSubSet的功能是判断集合B是否是集合A的子集。在IsSubSet中可以使用成员函数IsMembeOf睐判断一个正整数是否在此集合中,请编写成员函数IsSubSet。在main函数中给出了一组测试数据,此时程序的输出应该为:
集合A:1 2 3 5 8 10
集合B:2 8
集合B是集合A的子集
注意:只能在函数IsSubSet的“//********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处的元素
bool IsSubSet (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"
bool IntSet::IsSubSet(IntSet& set)
{
//******** 333********
//******** 666********
}
int main ()
{
int a[] = {1, 2, 3, 5, 8, 10};
int b[] ={2, 8};
IntSet set1 (a, 6), set2 (b, 2);
cout << "集合A:";
set1.Print ();
cout << "集合B:";
set2.Print ();
if (set1.IsSubSet (set2))
cout <<"集合B是集合A的子集" << endl;
else
cout <<"集合B不是集合A的子集" << endl;
writeToFile ("");
return 0;
}
【正确答案】if(end<set.GetEnd()) //如end小于set.GetEnd()
return false; //返回false
for(int i=0; i<=set.GetEnd(); i++) //i从0到set.GetEnd遍历
if (! IsMemberOf(set.GetElement (i))) //如果set.GetElement(i)不在对象集合中
return false; //返回false
return true; //否则返回true
【答案解析】[考点] 本题考查的是IntSet类,其中涉及数组、构造函数、bool函数和成员函数。
[解析] 主要考查考生对数组的掌握情况,题目要求完成函数bool IntSet::IsSubSet(IntSet&set)的函数体,该函数用来判断集合B是否是集合A的子集。使用for循环遍历集合B的每个元素,调用函数IsMemberOf判断每个元素是否是集合A中的元素,如果全是则集合B是集合A的子集,否则不是集合A的子集。