首先是 seqlist.h
template <typename T>
class seqlist
{
public:
seqlist(int capacity);
~seqlist();
int get_length(); //獲取長度
int get_capacity();//獲取容量
bool insert(int pos, T& t); //在pos位置插入一個元素
bool del(int pos, T& t); //在pos位置刪除一個元素
T& at(int pos); //在pos位置獲取一個元素
private:
int capacity; //容量
int length; //長度
T *p_array;
};
然後是seqlist.cpp
#include "seqlist.h"
template <typename T>
seqlist<T>::seqlist(int capacity)
{
p_array = new T[capacity];
this->capacity = capacity;
this->length = 0;
}
template <typename T>
seqlist<T>::~seqlist()
{
delete[] p_array;
p_array = NULL;
capacity = 0;
length = 0;
}
template <typename T>
int seqlist<T>::get_length() //獲取長度
{
return this->length;
}
template <typename T>
int seqlist<T>::get_capacity()//獲取容量
{
return this->capacity;
}
template <typename T>
bool seqlist<T>::insert(int pos, T& t) //在pos位置插入一個元素
{
int i;
for (i = length; i > pos; i--)
{
p_array[i] = p_array[i - 1];
}
p_array[i] = t; //對象複製!!
this->length++;
return true;
}
template <typename T>
bool seqlist<T>::del(int pos, T& t) //在pos位置刪除一個元素
{
if (pos <0 || pos >= get_length())
return false;
t = p_array[pos]; //對象複製!!
for (int i = get_length()-1; i > pos; i--)
{
p_array[i-1] = p_array[i];
}
this->length--;
return true;
}
template <typename T>
T& seqlist<T>::at(int pos) //在pos位置獲取一個元素
{
return p_array[pos];
}
一個測試文件
#include<iostream>
#include<list>
using namespace std;
#include "seqlist.cpp"
struct Teacher
{
public:
int age;
char name[32];
Teacher(){}
Teacher(int a, char* _name)
{
age = a;
strcpy_s(name, _name);
}
};
int main()
{
seqlist<Teacher> tlist(10);
Teacher t1(10,"張三"), t2(20, "李四"), t3(30,"王五"), t4(40, "孫六");
tlist.insert(0, t1);
tlist.insert(0, t2);
tlist.insert(0, t3);
tlist.insert(0, t4);
Teacher tmp;
cout << "tlist.at()" << endl;
for (int i = 0; i < tlist.get_length(); i++)
{
tmp = tlist.at(i);
cout << tmp.name << " :" << tmp.age << endl;
}
cout << "tlist.del()" << endl;
tlist.del(2,tmp);
cout << tmp.name << " :" << tmp.age << endl;
tlist.del(0,tmp);
cout << tmp.name << " :" << tmp.age << endl;
cout << "tlist.capacity():" <<tlist.get_capacity()<< endl;
system("pause");
return 0;
}
還未完善。。。