您的位置:首页 > 其它

一个简单的seqlist的模板实现

2017-04-23 21:52 330 查看
首先是 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;
}


还未完善。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: