c++开拓 » 输入两个5元素的集合,取并集 [c++]
时间:2010-09-21 来源:云之迦楼罗
#include <iostream.h>
#include <string.h>
#include <stdio.h>
class set
{
char a[5];
public:
void seta(char ele, int n)
{
a[n]=ele;
}
void disp();
friend void Union(set c, set b);
};
void set::disp()
{
int n;
for(n=0;n<=4;n++)
cout<<a[n];
cout<<endl;
}
void Union(set b,set c)
{
int n;
int m;
int o;
char a[11]={'0','0','0','0','0','0','0','0','0','0','0'};
strcpy(a,b.a); //将数组1复制给a
o=5; //取并集时,o从5开始计数
for(m=0;m<=4;m++) //取数组2种的第m个元素与数组1中个元素比较
{
for(n=0;n<o;n++) //取数组1种的第m个元素与数组2中个元素比较
{
if(a[n]==c.a[m]) //如果有相同元素,则跳出循环
{
break;
}
if(n==o-1) //当n与已复制的所有元素作了比较后……
{
a[o]=c.a[m];
o++;
continue;
}
}
}
cout<<"Union the two sets together are:"<<endl;
for(n=0;n<=o-1;n++)
{
cout<<a[n]<<" ";
}
};
void main()
{
set b;
set d;
int elenum;
int n;
char x[5];
cout<<"Please input the 5 element of Set A:"<<endl;
for(n=0;n<=4;n++)
{
loop1:
cin>>x[n];
if(n>=1)
{
for(elenum=0;elenum<=n-1;elenum++)
{
if(x[elenum]==x[n])
{
cout<<"wrong!!";
goto loop1;
}
}
}
b.seta(x[n],n);
}
b.disp();
cout<<endl<<"Please input the 5 element of Set B:"<<endl;
for(n=0;n<=4;n++)
{
loop2:
cin>>x[n];
if(n>=1)
{
for(elenum=0;elenum<=n-1;elenum++)
{
if(x[elenum]==x[n])
{
cout<<"wrong!!";
goto loop2;
}
}
}
d.seta(x[n],n);
}
cout<<endl<<"The two sets are:"<<endl;
b.disp();
d.disp();
set u(set b, set d);
Union(b,d);
cout<<endl;
}