c++实现并集(A∪B = C)

本文介绍了一个简单的C++程序实现,该程序定义了一个整数集合类int_set,支持基本的集合操作如并集,并且能够对两个集合进行排序及合并。通过用户输入集合A和集合B的元素,程序会输出这两个集合的并集C,同时确保集合内的元素是有序的。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>
using namespace std;

class int_set
{
private:
	int max_size;      //最大容量
	int current_size;  //当前大小
	int *p;            //动态数组

public:
	//构造函数
	int_set(int &arr_size) :max_size(arr_size), current_size(0)
	{
		this->p = new int[arr_size];
	}

	//拷贝构造函数
	int_set(const int_set &copy)
	{
		this->max_size = copy.max_size;
		this->current_size = copy.current_size;
		this->p = new int[copy.max_size];
		for (int i = 0; i < this->current_size; i++)
		{
			this->p[i] = copy.p[i];
		}
	}

	//析构函数
	~int_set()
	{
		delete[]p;
	}

	//查找相同元素
	int search(int &elem)
	{
		for (int i = 0; i < this->max_size; i++)
		{
			if (this->p[i] == elem)
			{
				return 1;
			}
			
		}
		return 0;
	}


	//输入
	void input()
	{
		for (int i = 0; i < this->max_size; i++)
		{
			cin >> p[i];
		}

		this->current_size = this->max_size;
	}

	//输出
	void ouput()
	{
		for (int i = 0; i < this->current_size; i++)
		{
			cout << p[i] << " ";
		}
	}

	//并集 + 排序(A ∪ B = C)
	int_set* elem_union(int_set *B)
	{
		
		int i, j;

		//动态开辟集合C的内存空间
		int new_max_size = this->max_size + B->max_size;
		int_set *C = new int_set(new_max_size);

		//排序集合A,放入集合C中
		C->p[0] = this->p[0];
		for (i = 1; i < this->max_size; i++)
		{
			for (j = i - 1; this->p[i] < C->p[j] && j >= 0; j--)
			{
				C->p[j + 1] = C->p[j];
			}
			C->p[j + 1] = this->p[i];
		}

		//更新C集合的当前大小
		C->current_size = this->max_size;
        
		//排序集合B,放入集合C中
		for (i = 0; i < B->max_size; i++)
		{
			if (!C->search(B->p[i])) //查找两个集合是否有相同元素
			{
				for (j = C->current_size - 1; B->p[i] < C->p[j] && j >= 0; j--)
				{
					C->p[j + 1] = C->p[j];
				}
				C->p[j + 1] = B->p[i];

				//更新C集合大小
				C->current_size++;
				
			}

		}

		return C;
	}

};



int main()
{
	int m = 0, n = 0;
	cout << "请输入A集合大小:" << endl;
	cin >> m;
	cout << "请输入B集合大小:" << endl;
	cin >> n;
	int w = m + n;
	int_set *A = new int_set(m);
	int_set *B = new int_set(n);
	int_set *temp = new int_set(w);
	cout << "请输入集合A元素:" << endl;
	A->input();
	cout << "请输入集合B元素:" << endl;
	B->input();
	temp = A->elem_union(B);
	cout << "集合C元素:" << endl;
	temp->ouput();
	
	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值