c++模板类实现线性表顺序存储
2016-10-05 11:49
477 查看
SeqList.h
test.cpp
#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; }
相关文章推荐
- 数据结构与算 5:C++ 顺序/链式存储,栈 模板类实现,编译模板类问题解决
- 线性表的顺序存储实现c++
- 线性表顺序存储(C++ 实现)
- 顺序存储线性表的C++实现——严蔚敏版《数据结构》
- 数据结构之循环队列(顺序表存储)——C++模板类实现
- 线性表的顺序存储实现
- 链表的顺序表示和实现(C++模板类实现)
- 线性结构的顺序存储和链式存储的实现代码(二)
- 数据结构:线性表的顺序存储--Java实现
- 线性表的顺序存储和链式存储的实现(C)
- 线性表的顺序存储及JAVA实现
- 线性表的顺序存储实现及相关操作 C语言版
- 线性表以顺序表为存储结构的实现(数据元素的类型为整型)
- 线性表顺序存储--C实现
- java实现线性表的顺序存储
- 线性表的顺序存储和链式存储的实现(C)
- 线性表的顺序存储及操作实现
- php线性表顺序存储实现代码(增删查改)
- 数据结构:线性表(顺序存储)顺序栈类(实现创建,输出,入栈出栈,读栈顶元素功能)
- 用C++模板实现线性表的链式存储的基本算法(数据结构C++版 北京科海)