模板类实现STL_Array

SeqList.h文件

#pragma once
#include <iostream>

using namespace std;

template <typename T>
class SeqList
{
public:
	SeqList(int capacity);
	~SeqList(void);

	int getLen();
	int getCapacity();
	int insert(T &t,int pos);
	int get(int pos,T &t);
	int del(int pos,T &t);

private:
	int len;
	int capacity;
	T *pArray;

};

SeqList.cpp文件

#include "SeqList.h"

template <typename T>
SeqList<T>::SeqList(int capacity)
{
	pArray = new T[capacity];
	this->len = 0;
	this->capacity = capacity;
}


template <typename T>
SeqList<T>::~SeqList(void)
{
	delete[] pArray;
	pArray = NULL;
	this->len = 0;
	this->capacity = 0;
}

template <typename T>
int SeqList<T>::getLen()
{
	return this->len;
}
template <typename T>
int SeqList<T>::getCapacity()
{
	return this->capacity;
}
template <typename T>
int SeqList<T>::insert(T &t,int pos)
{
	if (pos < 0)
	{
		return -1;
	}
	if (pos > this->capacity)
	{
		pos = this->capacity;
	}
	int i = 0;
	for (i=len;i>pos;i--)
	{
		pArray[i] = pArray[i-1];
	}
	pArray[i] = t;
	this->len++;
	return 0;
}
template <typename T>
int SeqList<T>::get(int pos,T &t)
{
	t = pArray[pos];
	return 0;
}
template <typename T>
int SeqList<T>::del(int pos,T &t)
{
	if (pos < 0 || pos > len)
	{
		return -1;
	}
	t = pArray[pos];
	for (int i=pos;i<this->len;i++)
	{
		pArray[i] = pArray[i+1];
	}
	this->len--;
	return 0;
}

SeqListTest.cpp文件

#include "SeqList.cpp"

struct Teacher
{
	char name[64];
	int age;
};

int main()
{
	Teacher t1,t2,t3;
	t1.age = 31;
	t2.age = 32;
	t3.age = 33;

	SeqList<Teacher> sList(10);

	sList.insert(t1,0);
	sList.insert(t2,0);
	sList.insert(t3,0);

	int len = sList.getLen();
	int cap = sList.getCapacity();

	Teacher tem;
	for (int i=0;i<len;i++)
	{
		sList.get(i,tem);
		cout << tem.age << " ";
	}
	cout << endl;

	while(sList.getLen() > 0)
	{
		sList.del(0,tem);
		cout << tem.age << " ";
	}
	cout << endl;

	system("pause");
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值