c++定义一个集合类,怎样用操作符重载实现交集并集运算
来源:学生作业帮助网 编辑:六六作业网 时间:2024/11/28 12:28:48
c++定义一个集合类,怎样用操作符重载实现交集并集运算
c++定义一个集合类,怎样用操作符重载实现交集并集运算
c++定义一个集合类,怎样用操作符重载实现交集并集运算
#include
#include
using namespace std;
template
class MySet
{
public:
MySet();
MySet(int s, const Type a[]);
MySet(const MySet &o);
void Empty();
bool IsEmpty() const;
bool IsMemberOf(const Type &m) const;
void Add(const Type &m);
Type Sub();
bool IsEqual(const MySet &o) const;
MySet operator&(const MySet &o);
MySet operator|(const MySet &o);
void Print();
private:
Type element[100];
int count;
};
template
MySet::MySet() : count(0)
{
}
template
MySet::MySet(int s, const Type a[]) : count(s)
{
for (int i = 0; i < s; ++i)
element[i] = a[i];
}
template
MySet::MySet(const MySet &o)
{
count = o.count;
for (int i = 0; i < count; ++i)
element[i] = o.element[i];
}
template
void MySet::Empty()
{
count = 0;
}
template
bool MySet::IsEmpty() const
{
return (count == 0);
}
template
bool MySet::IsEqual(const MySet &o) const
{
if ((count != o.count)
|| (IsEmpty() && !o.IsEmpty())
|| (!IsEmpty() && o.IsEmpty()))
return false;
for (int i = 0; i < count; ++i)
{
if (element[i] != o.element[i])
return false;
}
return true;
}
template
bool MySet::IsMemberOf(const Type &m) const
{
if (IsEmpty())
return false;
for (int i = 0; i < count; ++i)
{
if (element[i] == m)
return true;
}
return false;
}
template
void MySet::Add(const Type &m)
{
if (++count > 100)
return;
element[count - 1] = m;
}
template
Type MySet::Sub()
{
if (IsEmpty())
return 0;
Type temp = element[count];
--count;
return temp;
}
template
MySet MySet::operator&(const MySet &o)
{
MySet inset;
if (IsEmpty() || o.IsEmpty())
return inset;
for (int i = 0; i < count; ++i)
{
for (int j = 0; j < o.count; ++j)
if (element[i] == o.element[j] && !inset.IsMemberOf(o.element[j]))
inset.Add(element[i]);
}
return inset;
}
template
MySet MySet::operator|(const MySet &o)
{
MySet unset(count, element);
if (!IsEmpty() && o.IsEmpty())
return unset;
if (IsEmpty() && !o.IsEmpty())
return MySet(o);
for (int i = 0; i < count; ++i)
{
for (int j = 0; j < o.count; ++j)
if (element[i] != o.element[j] && !unset.IsMemberOf(o.element[j]))
unset.Add(o.element[j]);
}
return unset;
}
template
void MySet::Print()
{
for (int i = 0; i < count; ++i)
cout