Bài này tương tự dãy nhưng khó hơn là tập hợp thì không có phần tử trùng nhau, vì vậy khi code cũng nên hết sức cẩn thận:
- Code:
#include "iostream.h"
#include "stdio.h"
typedef struct
{
int n;
int a[100];
}taphop;
int ktra(taphop a,int n,int x);
void nhap(taphop &a);
void xuat(taphop a);
void them(taphop a,int k,int x);
void xoa(taphop a,int k);
int tim(taphop a,int x);
void hoi(taphop a,taphop b);
void giao(taphop a,taphop b);
void hieu(taphop a,taphop b);
void main()
{
taphop a,b;
int n,x,k;
cout<<"\nNhap tap A: ";
nhap(a);
cout<<"Tap hop A: ";
xuat(a);
them(a,k,x);
xoa(a,k);
if(tim(a,x)) cout<<"\nx xuat hien trong tap hop goc!";
else cout<<"\nx khong co trong tap hop!";
cout<<"\nNhap tap B: ";
nhap(b);
cout<<"Tap hop B: ";
xuat(b);
cout<<"\nHoi cua A va B: ";
hoi(a,b);
cout<<"\nGiao cua A va B: ";
giao(a,b);
cout<<"\nHieu cua A va B: ";
hieu(a,b);
}
int ktra(taphop a,int n,int x)
{
int i;
for(i=0;i<n;i++)
if(x==a.a[i]) return 1;
return 0;
}
void nhap(taphop &a)
{
int i,t=0;
cout<<"\nNhap vao so phan tu: ";
cin>>a.n;
for(i=0;i<a.n;i++)
{
cout<<"a["<<i<<"] = ";
cin>>a.a[i]; if(!ktra(a,t,a.a[i]))
a.a[t++]=a.a[i];
}
a.n=t;
}
void xuat(taphop a)
{
int i;
cout<<"{ ";
for(i=0;i<a.n;i++)
{
cout<<a.a[i]<<" ";
if(i!=a.n-1) cout<<","; else cout<<"}";
}
}
void them(taphop a,int k,int x)
{
int i;
cout<<"\nVi Tri & Gia tri them vao: ";
cin>>k>>x;
if(!ktra(a,a.n,x))
{
cout<<"\nTap hop goc sau khi them "<<x<<" vao vi tri "<<k<<": ";
for(i=a.n;i>k-1;i--)
a.a[i]=a.a[i-1];
a.a[k]=x; a.n++;
cout<<"Tap hop:";xuat(a);
}
else
{
cout<<"\nDa co san "<<x<<" khong the them!";
cout<<"\nTap hop goc: ";xuat(a);
}
}
void xoa(taphop a,int k)
{
int i;
cout<<"\nVi Tri can xoa: ";
cin>>k;
cout<<"Tap hop goc sau khi xoa vi tri "<<k<<": ";
for(i=k-1;i<a.n;i++)
a.a[i]=a.a[i+1];
a.n--;
xuat(a);
}
int tim(taphop a,int x)
{
int i;
cout<<"\nNhap gia tri can tim:";
cin>>x;
for(i=0;i<a.n;i++)
if(a.a[i]==x)
return 1;
return 0;
}
void hoi(taphop a,taphop b)
{
int i,j,k;
i=j=k=0;
taphop c;
while(i<a.n)
c.a[k++]=a.a[i++];
while(j<b.n) {
if(!ktra(a,a.n,b.a[j]))
c.a[k++]=b.a[j++];
else j++;
}
c.n=k;
xuat(c);
}
void giao(taphop a,taphop b)
{
int i,j,k=0;
taphop c;
for(i=0;i<a.n;i++)
for(j=0;j<b.n;j++)
if(b.a[j]==a.a[i])
c.a[k++]=a.a[i];
c.n=k; xuat(c);
}
void hieu(taphop a,taphop b)
{
int i,k=0;
for(i=0;i<a.n;i++)
if(!ktra(b,b.n,a.a[i]))
c[k++]=a.a[i];
c.n=k;
xuat(c);
}