题目:设计和实现整型集合类(Set)
成员函数要求如下:
1.添加构造函数完成初始化
2.能添加一个元素,元素不重复
3.能删除一个元素
4.输出所有元素
5.求两个集合对象的交集
6.求两个集合对象的并集
7.求两个集合对象的差集
#include <iostream>
using namespace std;
class Set{
public:
Set(){num=0;}//构造函数初始化
void add(int x);//添加
void del(int x);//删除
void output();
int find(int x);//查找
Set bingji(Set t);//并集
Set jiaoji(Set t);//交集
Set chaji(Set t);//差集
private:
int a[100];
int num;
};
void Set::add(int x){ //添加
if(find(x)==-1)
{
a[num]=x;
num++;
}
}
void Set::del(int x){ //删除
int i,pos;
pos=find(x);
if(pos!=-1){
for(i=pos;i<num-1;i++)
a[i]=a[i+1];
num--;
}
}
void Set::output(){ //输出
int i;
cout<<"{";
for(i=0;i<num;i++)
cout<<a[i]<<" ";
cout<<"}"<<endl;
}
int Set::find(int x){ //查找
int i;
for(i=0;i<num;i++)
if(a[i]==x)
return i;
return -1;
}
Set Set::bingji(Set t){ //并集
Set temp;
int i;
temp=*this;
for(i=0;i<t.num;i++)
temp.add(t.a[i]);
return temp;
}
Set Set::jiaoji(Set t){ //交集
Set temp,count;
int i,j;
count=*this;
for(i=0;i<count.num;i++){
for(j=0;j<t.num;j++){
if(count.a[i]==t.a[j]) {
temp.add(count.a[i]);
}
}
}
return temp;
}
Set Set::chaji(Set t){ //差集
Set temp,count;
int i,j,flag;
temp=*this;
for(i=0;i<t.num;i++){
temp.add(t.a[i]);
}
for(i=0;i<temp.num;i++){
flag=0;
for(j=0;j<t.num;j++){
if(temp.a[i]==t.a[j]) {
flag=1;
}
}
if(flag==0){
count.add(temp.a[i]);
}
}
return count;
}
int main()
{
Set s1,s2;
s1.add(10);
s1.add(11);
s1.add(12);
s1.add(13);
s1.add(14);
s1.del(10);//删除
s1.del(14);//删除
cout<<"集合s1为:" ;
s1.output();
s2.add(8);
s2.add(9);
s2.add(10);
s2.add(11);
s2.add(12);
s2.del(8);//删除
s2.del(12);//删除
cout<<"集合s2为:";
s2.output();
cout<<"交集为:"<<endl;
s1.jiaoji(s2).output();
cout<<"并集为:"<<endl;
s1.bingji(s2).output();
cout<<"差集为:"<<endl;
s1.chaji(s2).output();
return 0;
}
代码运行结果:
![](https://img-blog.csdnimg.cn/img_convert/5127f8e9cd96bdd6c33136d7dc61d4fe.png)