建立一个类Intersection求两个整数集合的交集,具体要求如下:
(1)私有数据成员
int set[20];用数组空间set存储集合
int len;表示该集合中元素的个数
(2)公有成员函数
Intersection(int *s,int l);构造函数,用l初始化其长度
Intersection();构造函数,将set的长度初始化为0
int f(int num):判断num是否属于集合,属于返回1,不属于返回0
Intersection operator&&( Intersection t):重载&&,求当前对象集合和参数对象t的集合交集,方法为:使用对象t的集合中的每个元素作为函数f的参数,若该元素属于当前对象的集合,则将其复制给交集
Void show();输出集合
(3)定义两个集合并初始化,求这两个集合的交集
#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<string>
using namespace std;
class Intersection
{
private:
int set[20];
int len;
public:
Intersection(int* s, int l)
{
len = l;
for (int i = 0; i < 20; i++)
set[i] = 0;
for (int i = 0; i < l; i++)
set[i] = *(s+i);
}
Intersection(){ len = 0; }
int fun(int num);
Intersection operator&&(Intersection t)
{
Intersection a;
int j = 0;
if (len > t.len)
{
for (int i = 0; i < len; i++)
{
if (fun(t.set[j]))
{
a.set[j] = t.set[j];
j++;
}
}
}
else
{
for (int i = 0; i < t.len; i++)
{
if (fun(t.set[j]))
{
a.set[j] = t.set[j];
j++;
}
}
}
a.len = j;
return a;
}
void show();
};
int Intersection::fun(int num)
{
for (int i = 0; i < len; i++)
if (num == set[i])
return 1;
return 0;
}
void Intersection::show()
{
for (int i = 0; i < len; i++)
cout << set[i] << " ";
cout << endl;
}
int main()
{
int a[10] = { 2,3,5,7,11,13,17,19,23,29 };
int b[5] = { 2,7,13,19,23 };
Intersection A(a, 10);
Intersection B(b, 5);
cout << "集合1的元素是:";
for (int i = 0; i < 10; i++)
cout << a[i] << " ";
cout << endl;
cout << "集合2的元素是:";
for (int i = 0; i < 5; i++)
cout << b[i] << " ";
cout << endl;
Intersection C;
C = A && B;
cout << "交集为:";
C.show();
return 0;
}