赞
踩
SeqList.h
- #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;
- }
- #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;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。