1. 程式人生 > >面向物件程式設計(C++) 示例程式——集合類

面向物件程式設計(C++) 示例程式——集合類

#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;
}