数据结构与算法分析 练习1.13 设计一个类模板Collection

1.14 设计一个类模板Collection,以存储(在一个数组中的)Object 对象的集合,以及该集合的当前大小。提供public 函数isEmpty 、makeEmpty、insert、remove以及contains.  contains(x) 返回true, 当且仅当在该集合中存在等于x 的Object。

#pragma once
#include <string>
#include <vector>

template <typename Object>
class Collection {
public:
	Collection() = default;
	Collection(Object oj) :obj(oj){}
	Object getObj() { return obj; }
	
	bool isEmpty() { return obj.size() ? false : true; }

	Collection<Object> & operator = (Collection<Object> & a) { *this = a; }

	~Collection() { };  // equal  : void

	template <typename T>
	Object insert(T apl) {
		Object temp;
		temp.resize(obj.size() + 1);
		
		for (size_t i = 0; i < obj.size(); i++)
		{
			temp[i] = obj[i];
		}
		temp[temp.size()-1] = apl;
		obj = temp;
		return obj;
	}

	template <typename T>
	bool contains(T in) {

		if (obj.size() == 0) { return false; }

		for (auto ob : obj) {
			if (in == ob)
				return true;
		}
		return false;
	}

	template <typename T>
	void remove(T oup) {
		if (obj.size() == 0) { return; }
		int count = 0;
		for (size_t i = 0; i < obj.size(); i++) {
			if (oup == obj[i]) {
				obj[i] = NULL;
				count++;
			}
		}
		Object temp;
		temp.resize(obj.size() - 1);
		int i = 0;
		
		for(auto ob : obj) {
			if (ob != NULL) {
				temp[i] = ob;
				i++;
			}
		}
		obj = temp;

	}

	void print() { for (auto each : obj)  cout << each << " "; cout << endl; }

private:
	Object obj;
};



#include <iostream>

#include "collection.h"

using namespace std;
int main()
{
	vector<int> a = { 1,2,3,4,5 };
	vector<int>  b;
	Collection<vector<int>>  c(a);
 	Collection<string> stc ;

	cout << c.getObj().at(1) << endl;
	c.insert<int>(6);
	cout <<"C after inserted :  "<< c.getObj()[5] << endl;
	c.remove(3);
	cout <<"c.constains(3) true or false: " <<c.contains(4) << endl;
	c.print();
	c.~Collection();
	cout <<"c.isEmpty() true or false: "<< c.isEmpty() << endl;
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值