2016/6/3 1000. Class Set

这道题要求设计的类是一个集合。然后这个集合是需要用模板实现的,也就是说可能的类型有很多种。数据成员中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();
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值