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;
}