参考了修改了网上的代码
http://blog.csdn.net/yycec/article/details/7361067
#include <iostream> #include <string> #include <memory.h> using namespace std; template <class T> class Set { int maxsize; //集合的当前最大容量 int count; //集合的当前元素个数 T *elem; public: Set<T>(int initsize=10); //构造函数,创建一个空集,initsize: 集合的初始容量 Set<T>(const Set<T>& s); //拷贝构造函数 ~Set(); //析构函数 int Add(T a[], int len); //增加一组新元素,返回值为新增加的元素个数 int Add(T e); //增加一个新元素,返回值为新增加的元素个数 bool Contains(T e) const; //检查当前集合中是否已包含元素 e Set<T> Intersect(Set<T>& s); //求与另一集合的交集 Set<T> Union(const Set<T>& s) const; //求与另一集合的并集 int GetCount() const; //获取当前集合中的元素个数 void Print() const; //打印所有元素 };//注:const 表示该函数不会对当前对象的数据成员做出修改 template<class T> void Set<T>::Print() const { for (int i = 0; i < count; i++) cout << elem[i] << " "; cout << endl; } template<class T> Set<T> Set<T>::Union(const Set<T>& s) const { Set<T> r(s); //用 s 来初始化新集合 r.Add(elem, count); //再添加入当前集合中包含的内容 return r; } template<class T> inline int Set<T>::GetCount() const { return count; } template<class T> Set<T> Set<T>::Intersect(Set<T>& s) { Set<T> 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; } template<class T> Set<T>::Set<T>(const Set<T>& s) { maxsize = s.maxsize; count = s.count; elem = new T[maxsize]; //为新元素分配空间 memcpy(elem, s.elem, sizeof(T)*count); //复制所有元素 } template<class T> Set<T>::~Set<T>() { //delete[] elem; //释放占用空间 } template<class T> Set<T>::Set<T>(int initsize) :maxsize(initsize), count(0) { elem = new T [maxsize]; if (!elem) throw "申请集合空间失败!"; } template<class T> int Set<T>::Add(T a[], int len) { int c = 0; //用于记录新增加的元素个数 for (int i = 0; i < len; i++) c+= Add(a[i]); return c; } template<class T> int Set<T>::Add(T e) { if (Contains(e)) return 0; //当前集合中已包含了指定元素,不用添加了。 if (count == maxsize) //空间已满,再增加空间 { T *tmp = new T[maxsize+10]; if (!tmp) return 0; //申请新空间失败,退出 memcpy(tmp, elem, count*sizeof(T)); //将原来的内容复制到新空间中 maxsize += 10; //最大容量增长10个数据单位 delete[] elem; //删除原有空间 elem = tmp; //将新空间的地址保存下来 } elem[count++] = e; //将新元素存放在数组的最后 return 1; } template<class T> bool Set<T>::Contains(T e) const { for (int i = 0; i < count; i++) if (elem[i] == e) return true; return false; }