c++ 设计和实现整型集合类(Set)

题目:设计和实现整型集合类(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;
}

代码运行结果:

  • 10
    点赞
  • 62
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值