c++模板类实现线性表顺序存储

SeqList.h

#pragma once
template<typename T>

class SeqList
{
public:
    SeqList(void);
    SeqList(int capacity);
    ~SeqList(void);
    int getLength();
    int getCapacity();
    int insert(T &t,int pos);
    int get(int pos,T&);
    int del(int pos,T&);
    int clear();
private:
    int length;
    int capacity;
    T *pArray;//数组
};

SeqList.cpp

#include "SeqList.h"

template<typename T>
SeqList<T>::SeqList(void)
{
}

template<typename T>
SeqList<T>::SeqList(int capacity)
{
	//T *pArray;//数组
	this->pArray = new T[capacity];
	this->capacity = capacity;
	this->length = 0;
}

template<typename T>
SeqList<T>::~SeqList(void)
{
	delete[] this->pArray;
	this->pArray = NULL;
	this->length = 0;
	this->capacity = 0;
}
template<typename T>
int SeqList<T>::getLength()
{
	return this->length;
}
template<typename T>
int SeqList<T>::getCapacity()
{
	return this->capacity;
}
template<typename T>
int SeqList<T>::insert(T &t,int pos)
{
	int i;
	if (pos<0)
	{
		return -1;
	}
	//元素后移
	for (i = this->length; i>pos;i--)
	{
		this->pArray[i] = this->pArray[i-1];
	}
	//在pos位置插入元素
	this->pArray[i] = t;//stl元素的保存 时通过赋值的机制实现的 深拷贝浅拷贝
	this->length++;

	return 0;
}
template<typename T>
int SeqList<T>::get(int pos,T&t)
{
	if (pos<0)
	{
		return -1;
	}
	t = this->pArray[pos];
	return 0;
}
template<typename T>
int SeqList<T>::del(int pos,T&t)
{
	t = this->pArray[pos];//保存要删除的节点元素值
	//元素前移
	for (int i = pos ;i <=this->length;i++)
	{
		this->pArray[i] = this->pArray[i+1];
	}
	this->length--;
	return 0;
}
template<typename T>
int SeqList<T>::clear()
{
    this->length = 0;
    return 0;
}

test.cpp

#include <iostream>
//#include "SeqList.h"//模板类两次编译 需要包含cpp
#include "SeqList.cpp"
using namespace std;

struct Teacher
{
	char name[20];
	int age;
};
void display()
{
	Teacher t1,t2,t3;
	Teacher tmp;
	SeqList<Teacher> list(10);
	t1.age = 10;
	t2.age = 20;
	t3.age = 30;
	list.insert(t1,0);
	list.insert(t2,0);
	list.insert(t3,0);

	for (int i =0;i<list.getLength();i++)
	{

		list.get(i,tmp);
		cout<<tmp.age<<endl;
	}
	//链表的删除
	while(list.getLength()>0)
	{
		list.del(0,tmp);
		cout<<tmp.age<<endl;
	}
}

void display_p()
{
	Teacher *p1,*p2,*p3;
	Teacher t1,t2,t3;
	Teacher *tmp;
	SeqList<Teacher*> list(10);
	p1 = &t1;
	p2 = &t2;
	p3 = &t3;

	t1.age = 10;
	t2.age = 20;
	t3.age = 30;
	list.insert(p1,0);
	list.insert(p2,0);
	list.insert(p3,0);

	for (int i =0;i<list.getLength();i++)
	{

		list.get(i,tmp);
		cout<<tmp->age<<endl;
	}
	//链表的删除
	while(list.getLength()>0)
	{
		list.del(0,tmp);
		cout<<tmp->age<<endl;
	}
}
int main()
{
	display_p();
	system("pause");
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值