#include <iostream>
#include <string>
#include <memory.h>
using namespace std;
class Set
{
int maxsize; //集合的当前最大容量
int count; //集合的当前元素个数
int *elem;
public:
Set(int initsize=10); //构造函数,创建一个空集,initsize: 集合的初始容量
Set(const Set& s); //拷贝构造函数
~Set(); //析构函数
int Add(int a[], int len); //增加一组新元素,返回值为新增加的元素个数
int Add(int e); //增加一个新元素,返回值为新增加的元素个数
bool Contains(int e) const; //检查当前集合中是否已包含元素 e
Set Intersect(const Set& s) const; //求与另一集合的交集
Set Union(const Set& s) const; //求与另一集合的并集
int GetCount() const; //获取当前集合中的元素个数
void Print() const; //打印所有元素
};//注:const 表示该函数不会对当前对象的数据成员做出修改
void main()
{
int a[]={1,3,5,7,9}, b[]={2,4,6,8,10,3, 5};
Set s1, s2;
s1.Add(a, 5);
s2.Add(b, 7);
Set s3 = s1.Intersect(s2);
Set s4 = s1.Union(s2);
s3.Print();
s4.Print();
}
void Set::Print() const
{
for (int i = 0; i < count; i++) cout << elem[i] << " ";
cout << endl;
}
Set Set::Union(const Set& s) const
{
Set r(s); //用 s 来初始化新集合
r.Add(elem, count); //再添加入当前集合中包含的内容
return r;
}
inline int Set::GetCount() const
{
return count;
}
Set Set::Intersect(const Set& s) const
{
Set r(s.count + this->count);
for (int i = 0; i < s.count; i++)
{
if (Contains(s.elem[i])) r.Add(s.elem[i]); //两个集合中都有的元素,加入到交集中。
}
return r;
}
Set::Set(const Set& s)
{
maxsize = s.maxsize;
count = s.count;
elem = new int[maxsize]; //为新元素分配空间
memcpy(elem, s.elem, sizeof(int)*count); //复制所有元素
}
Set::~Set()
{
delete[] elem; //释放占用空间
}
Set::Set(int initsize)
:maxsize(initsize), count(0)
{
elem = new int [maxsize];
if (!elem) throw "申请集合空间失败!";
}
int Set::Add(int a[], int len)
{
int c = 0; //用于记录新增加的元素个数
for (int i = 0; i < len; i++) c+= Add(a[i]);
return c;
}
int Set::Add(int e)
{
if (Contains(e)) return 0; //当前集合中已包含了指定元素,不用添加了。
if (count == maxsize) //空间已满,再增加空间
{
int *tmp = new int[maxsize+10];
if (!tmp) return 0; //申请新空间失败,退出
memcpy(tmp, elem, count*sizeof(int)); //将原来的内容复制到新空间中
maxsize += 10; //最大容量增长10个数据单位
delete[] elem; //删除原有空间
elem = tmp; //将新空间的地址保存下来
}
elem[count++] = e; //将新元素存放在数组的最后
return 1;
}
bool Set::Contains(int e) const
{
for (int i = 0; i < count; i++)
if (elem[i] == e) return true;
return false;
}面向对象程序设计(C++) 示例程序——集合类
最新推荐文章于 2025-11-09 19:18:58 发布
本文介绍了一个简单的集合类实现,包括并集、交集等基本操作。通过C++代码展示了如何进行元素添加、查找及集合间的运算。

2337

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



