顺序表实现

来源:互联网 发布:小猪cms系统价格 编辑:程序博客网 时间:2024/06/15 10:56
sqlist.h
#ifndef SQLIST#define SQLIST#define NOT_FOUND              -1#define ERROR_LIST_FULL        -2#define ERROR_LIST_OVERSTEP    -3#define ERROR_LIST_ILLEGALNUM  -4#define null                    0#define SUCCEED                 1template <class Data> class sqlist{private:int length;Data * data;int full;public:sqlist(int);int insert(Data&,int);int del(int);int search(const Data&);Data get(int);Data add(Data&);};
#include "sq_list.h"
#endif


sq_list.h

template <class Data> sqlist<Data>::sqlist(int s){data=new Data[s];length=0;full=s;}template <class Data> int sqlist<Data>::insert(Data& d,int p){if(length==full)return ERROR_LIST_FULL;if(p>length)return ERROR_LIST_OVERSTEP;if(p<0)return ERROR_LIST_ILLEGALNUM;for(int i=length-1;i>p;i--){data[i]=data[i-1];}data[p]=d;length++;return SUCCEED;}template <class Data> int sqlist<Data>::search(const Data& d){int p=0;for(;p<length;p++){if(data[p]==d)return p;}return NOT_FOUND;}template <class Data> int sqlist<Data>::del(int p){if(p>=length)return ERROR_LIST_OVERSTEP;if(p<0)return ERROR_LIST_ILLEGALNUM;for(int i=p;i<length-2;i++){data[i]=data[i+1];}length--;return SUCCEED;}template <class Data> Data sqlist<Data>::get(int p){if(p<0)return null;if(p>=length)return null;return data[p];}

    使用申明与实现分离的策略,但是又由于使用的是模版类来实现的,gnu/gcc已经不提供对export的支持了,被引用时有编译多态,其实现源代码必须在引用文件中可见,所以其实现被封装在头文件中,包含于每一个引用此类的文件中,编译时再由编译器根据传入的参数类型对其进行实例化。