这道题要求设计的类是一个集合。然后这个集合是需要用模板实现的,也就是说可能的类型有很多种。数据成员中data很明显就是储存数据了,maxSize和count是分别记录最大元素个数和当前元素个数的int。还有比较麻烦的就是接口的实现。增加元素要注意不要重复添加,不要超过maxSize,删除要找到目标后覆盖掉,同时两个操作都要记得对count操作。列举就很简单了,看清楚最后面有没有空格就可以了。并集的话实际上就是在是s1的基础上插入每一个s2的元素,差集则是去除每一个s2的元素。最后实现起来也不是很困难。
#include <iostream>
using namespace std;
template< typename T >
class Set
{
public:
Set()
{
data = new T[0];
maxSize = 0;
count = 0;
}
Set(int maxSize_)
{
maxSize = maxSize_;
data = new T[maxSize];
count = 0;
}
~Set()
{
delete[] data;
}
Set(const Set& s)
{
maxSize = s.getMaxSize();
count = s.getCount();
data = new T[maxSize];
for (int i = 0; i <= count - 1; i++)
{
data[i] = s.data[i];
}
}
Set operator+(const Set& s)
{
Set sum(count + s.count);
for (int i = 0; i <= count - 1; i++)
{
sum.insert(data[i]);
}
for (int i = 0; i <= s.count - 1; i++)
{
sum.insert(s.data[i]);
}
return sum;
}
Set operator-(const Set& s)
{
Set dif = (*this);
for (int i = 0; i <= s.count - 1; i++)
{
dif.erase(s.data[i]);
}
return dif;
}
void operator=(const Set& s)
{
maxSize = s.getMaxSize();
count = s.getCount();
data = new T[maxSize];
for (int i = 0; i <= count - 1; i++)
{
data[i] = s.data[i];
}
}
bool insert(T newItem)
{
for (int i = 0; i <= count - 1; i++)
{
if (newItem == data[i])
{
return false;
}
}
if (count + 1 <= maxSize)
{
data[count++] = newItem;
return true;
}
else return false;
}
bool erase(T targetItem)
{
for (int i = 0; i <= count - 1; i++)
{
if (targetItem == data[i])
{
count--;
for (int j = i; j <= count - 1; j++)
{
data[j] = data[j + 1];
}
return true;
}
}
return false;
}
void print() const
{
for (int i = 0; i <= count - 1; i++)
{
cout << data[i] << " ";
}
cout << endl;
}
T* getData() const
{
return data;
}
int getCount() const
{
return count;
}
int getMaxSize() const
{
return maxSize;
}
private:
int count;
int maxSize;
T* data;
};
int main()
{
Set<int> s1(10), s2(10), s_plus, s_minus;
s1.insert(1);
s1.insert(2);
s1.insert(2);
s1.insert(4);
cout << "Items in s1 are : ";
s1.print();
s2.insert(3);
s2.insert(3);
s2.insert(1);
s2.insert(2);
cout << "Items in s2 are: ";
s2.print();
s_plus = s1 + s2;
cout << "Items in s_plus are: ";
s_plus.print();
s_minus = s1 - s2;
cout << "Items in s_minus are: ";
s_minus.print();
}