#include<iostream>
#include<vector>
using namespace std;
template<typename T>
class Set
{
private:
vector<T> data;
protected:
bool Find(T d)//查找
{
vector<T>::iterator itr;
for(itr=data.begin();itr!=data.end();itr++)
if(*itr==d)return true;
return false;
}
public:
Set(){data.clear();}
Set(vector<T> dd){data=dd;}
Set(const Set&s){data=s.data;}
~Set(){data.clear();}
bool Add(T d)
{
vector<T>::iterator itr=data.begin();
for(;itr!=data.end();itr++)
if(*itr==d) return false;
data.push_back(d);return true;
}
bool BeIncluded(Set<T>s)//当前集合是否包含于集合s
{
vector<T>::iterator itr;
for(itr=data.begin();itr!=data.end();itr++)
if(!s.Find(*itr)) return false;
return true;
}
void Clear(){data.clear();}
bool Delete(T d)//按值删除
{
vector<T>::iterator itr=data.begin();
for(;itr!=data.end();itr++)
if(*itr==d)
{
data.erase(itr);
return true;//返回
}
return false;
}
bool DeleteByIndex(int n)//按秩删除
{
if(n>=data.size()||n<0) return false;
data.erase(data.begin()+n);return true;
}
bool Empty(){return data.empty();}
bool Include(Set<T>s){return s.BeIncluded(*this);}
int Scale(){return data.size();}//判断规模
void Show()
{
vector<T>::iterator itr=data.begin();
for(;itr!=data.end();itr++)
cout<<*itr<<",";
cout<<endl;
}
Set<T> operator-(Set<T>&s)
{
Set<T>result(*this);
vector<T>::iterator itr;
for(itr=s.data.begin();itr!=s.data.end();itr++)
if(result.Find(*itr))
result.Delete(*itr);
return result;
}
bool operator==(Set<T>&s)//要考虑元素的无序性。
{
vector<T>::iterator itr;
for(itr=data.begin();itr!=data.end();itr++)
if(!s.Find(*itr)) return false;
return data.size()==s.data.size();
}
friend Set<T> Intersection(Set<T>&A,Set<T>&B);
friend Set<T> Union(Set<T>&A,Set<T>&B);
};
template<typename T>
Set<T> Intersection(Set<T>& A, Set<T>&B)
{
Set<T>result;
vector<T>::iterator itr;
for(itr=A.data.begin();itr!=A.data.end();itr++)//通过友元关系访问私有成员data
if(B.Find(*itr)) result.Add(*itr);
return result;
}
template<typename T>
Set<T> Union(Set<T>&A,Set<T>&B)
{
Set<T>result(A);
vector<T>::iterator itr;
for(itr=B.data.begin();itr!=B.data.end();itr++)
result.Add(*itr);
return result;
}
int main()
{
Set<int> s1;
s1.Add(3);s1.Add(9);s1.Add(40);
Set<int> s2(s1);
s1.Add(33);s2.Add(44);
cout<<"集合一:";s1.Show();
cout<<"集合二:";s2.Show();
Set<int> s3=Intersection(s1,s2);
cout<<"交集:";s3.Show();
Set<int> s4=Union(s1,s2);
cout<<"并集:";s4.Show();
Set<int>s5=s1-s2;
cout<<"集合一减去集合二:";s5.Show();
s5.Clear();s5=s2-s1;
cout<<"集合二减去集合一:";s5.Show();
cout<<"被包含关系:"<<s5.BeIncluded(s2)<<endl;
cout<<"包含关系:"<<s2.Include(s3)<<endl;
cout<<"集合二规模:"<<s2.Scale()<<"集合四规模:"<<s4.Scale()<<endl;
Set<int>s6;s6.Add(9);s6.Add(3);s6.Add(40);s6.Add(33);
cout<<"集合一与集合六判等:"<<(s1==s6)<<endl;
cout<<"集合二与集合六判等:"<<(s2==s6)<<endl;
return 0;
}
//写了个有点冗余的,可能还没有你自己的写得好。