C++求两个集合的交集

建立一个类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;
}


  • 8
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值