c++模板库线性表线性存储实现实现

SeqList.h

#pragma once

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

public:
	int SeqList_Length();
	int SeqList_Capacity();
	int SeqList_Insert(T &t, int pos);
	int SeqList_Get(T &t, int pos);
	int SeqList_Delete(T &t, int pos);

private:
	int length;
	int capacity;
	T *pArray;      //数组
};


SeqList.cpp

#include<iostream>
#include"SeqList.h"
using namespace std;

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

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


template<typename T>
int SeqList<T>::SeqList_Length()
{
	return this->length;
}

template<typename T>
int SeqList<T>::SeqList_Capacity()
{
	return this->capacity;
}

template<typename T>
int SeqList<T>::SeqList_Insert(T &t, int pos)
{
	int i;
	if ( pos< 0)
	{
		return -1;
	}
	for (i = length; i>pos; i--)
	{
		pArray[i] = pArray[i - 1];
	}    

	pArray[i] = t;
	this->length++;
	return 0;
}

template<typename T>
int SeqList<T>::SeqList_Get(T &t,int pos)
{
	if (pos< 0)
	{
		return -1;
	}
	t = pArray[pos];
	return 0;
}

template<typename T>
int SeqList<T>::SeqList_Delete(T &t,int pos)
{
	if ( pos< 0)
	{
		return -1;
	}
	t = pArray[pos];
	for (int i = pos + 1; i < len; i++)
	{
		pArray[i - 1] = pArray[i];
	}
	len--;
	return 0;
}


Test.cpp

#include<iostream>
#include"SeqList.cpp"
using namespace std;




struct Teacher
{
	int age;
};

void main11()
{
	SeqList<int> list(10);
	int a = 1;
	int b = 2;
	int c = 3;
	list.SeqList_Insert(a, 0);
	list.SeqList_Insert(b, 0);
	list.SeqList_Insert(c, 0);

	for (int i = 0; i < list.SeqList_Length(); i++)
	{
		int t;
		list.SeqList_Get(t, i);
		cout << t << endl;
	}

	system("pause;");
}

void main()
{
	Teacher t1, t2, t3;
	t1.age = 1;
	t2.age = 2;
	t3.age = 3;
	SeqList<Teacher> list(10);
	list.SeqList_Insert(t1, 0);
	list.SeqList_Insert(t2, 0);
	list.SeqList_Insert(t3, 0);

	for (int i = 0; i < list.SeqList_Length(); i++)
	{
		Teacher t3;
		list.SeqList_Get(t3, i);
		cout << t3.age << endl;
	}
	system("pause;");
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值