c++定义一个集合类,怎样用操作符重载实现交集并集运算

c++定义一个集合类,怎样用操作符重载实现交集并集运算

第1个回答  2009-04-29
#include <iostream>
#include <string>

using namespace std;

template <typename Type>
class MySet
{
public:
MySet();
MySet(int s, const Type a[]);
MySet(const MySet<Type> &o);

void Empty();
bool IsEmpty() const;
bool IsMemberOf(const Type &m) const;
void Add(const Type &m);
Type Sub();
bool IsEqual(const MySet<Type> &o) const;
MySet<Type> operator&(const MySet<Type> &o);
MySet<Type> operator|(const MySet<Type> &o);
void Print();

private:
Type element[100];
int count;
};

template <typename Type>
MySet<Type>::MySet() : count(0)
{
}

template <typename Type>
MySet<Type>::MySet(int s, const Type a[]) : count(s)
{
for (int i = 0; i < s; ++i)
element[i] = a[i];
}

template <typename Type>
MySet<Type>::MySet(const MySet &o)
{
count = o.count;

for (int i = 0; i < count; ++i)
element[i] = o.element[i];
}

template <typename Type>
void MySet<Type>::Empty()
{
count = 0;
}

template <typename Type>
bool MySet<Type>::IsEmpty() const
{
return (count == 0);
}

template <typename Type>
bool MySet<Type>::IsEqual(const MySet<Type> &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 <typename Type>
bool MySet<Type>::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 <typename Type>
void MySet<Type>::Add(const Type &m)
{
if (++count > 100)
return;

element[count - 1] = m;
}

template <typename Type>
Type MySet<Type>::Sub()
{
if (IsEmpty())
return 0;

Type temp = element[count];
--count;

return temp;
}

template <typename Type>
MySet<Type> MySet<Type>::operator&(const MySet<Type> &o)
{
MySet<Type> 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 <typename Type>
MySet<Type> MySet<Type>::operator|(const MySet<Type> &o)
{
MySet<Type> 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 <typename Type>
void MySet<Type>::Print()
{
for (int i = 0; i < count; ++i)
cout << element[i] << ' ';
cout << endl;
}

int main()
{
int ia[7] = { 1, 2, 3, 4, 5, 6, 7 };
MySet<int> a, b(7, ia);
a.Add(6);
a.Add(7);
a.Add(8);
a.Add(9);
a.Print();
b.Print();
MySet<int> c = a | b;
MySet<int> d = a & b;
c.Print();
d.Print();
MySet<string> str;
str.Add("Hello");
str.Add("World!");
str.Print();
return 0;
}本回答被提问者采纳
相似回答