问答题 请使用VC6或使用[答题]菜单打开考生文件夹proj3下的工程proj3,其中声明的IntSet是一个用于表示正整数集合的类。IntSet的成员函数Merge的功能是求当前集合与另一个集合的并集,在Merge中可以使用成员函数IsMemberOf判断一个正整数是否在集合中。请完成成员函数Merge。在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 1 2 3 5 8 10 9 11 30 56 67 要求: 补充编制的内容写在“//********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 Merge(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::Merge(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.Merge(set2); cout << endl << "求并集后: " << endl; set1.Print(); set2.Print(); set3.Print(); writeToFile(""); return 0; }
【正确答案】for(int i=0; i<=end; i++) //i从零开始到end遍历,即实现把数组element复制到数组a[i] { a[i]=element[i]; //把element[i]赋值给a[i] size++; //size自加1 } for(int k=0; k<=set.GetEnd(); k++) //k从0至4 set.GetElement遍历 if(!IsMemberOf(Set.GetElement (k))) //如果set.GetElement(k)不是element中的元素 a[size++]=set.GetElement(k); //把set.GetElement(k)放到数组a中
【答案解析】[考点] 本题考查的是IntSet类,其中包括构造函数、bool函数和成员函数。 [解析] 主要考查考生对数组的掌握情况,题目要求计算集合的并集,定义一个新集合a,先复制一个数组的元素,再判断另一个数组中的元素,只要元素不重复就添加到集合a中。