1、建立一个类 Intersection,求两个整数集合的交集,具体要求如下:
(1)私有数据成员
int set[20]/用数组空间存放数据集合
int len//集合中元素的个数.
原题目
源代码
#include <iostream>
#include<cmath>
#include<string>
using namespace std;
class Intersection {
public:
//初始化
Intersection(int* s, int l) {
for (int i = 0; i < l; i++)set[i] = s[i];
len = l;
}
Intersection() {
for (int i = 0; i < 20; i++)set[i] =0;
len = 0;
}
int f(int num) {
for (int i = 0; i < len; i++) {
if (num == set[i]) return 1;
}
return 0;
}
void Setnum(int num, int n) { set[n] = num; len=n+1; }
Intersection operator&&(Intersection t) {
Intersection t2;
int j = 0;
for (int i = 0; i < len; i++) {
if (t.f(set[i])){
t2.Setnum(set[i],j);
j++;
}
}
return t2;
}
void show() {
for (int i = 0; i < len; i++) {
cout << set[i] << " ";
}
cout << endl;
}
private:
int set[20];//用数组空间存放数据集合
int len;//集合中元素的个数
};
int main() {
int s1[20] = { 1, 3, 4, 5, 7, 8 };
int s2[20] = { 1,2,3,5,7,9,11 };
Intersection obj1(s1, 6), obj2(s2, 7), obj3;
obj3 = obj1 && obj2;
cout << "obj1: "; obj1.show();
cout << "obj2: "; obj2.show();
cout << "obj1,obj2交集:"; obj3.show();
return 0;
}