#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 ©)
{
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;
}
c++实现并集(A∪B = C)
最新推荐文章于 2023-06-24 19:44:12 发布
本文介绍了一个简单的C++程序实现,该程序定义了一个整数集合类int_set,支持基本的集合操作如并集,并且能够对两个集合进行排序及合并。通过用户输入集合A和集合B的元素,程序会输出这两个集合的并集C,同时确保集合内的元素是有序的。

1072

被折叠的 条评论
为什么被折叠?



