1. 程式人生 > >C++實現順序表的使用

C++實現順序表的使用

#include <iostream> using namespace std; template<class T> class SeqList  { protected:     T *element;//動態陣列儲存順序表的資料元素     int length;//順序表的陣列容量     int n;//順序表的個數 public:     void init(T values[],int n)//初始化順序表     {         this->length=n*2;//開闢2n的空間         this->element=new int[this->length];         this->n=n;         for (int i=0;i<n;i++)         {             this->element[i]=values[i];//執行int的賦值,         }                  }     SeqList(int length=32)//構造空表     {         this->element=new int[length];         this->length=length;         this->n=0;     }     SeqList(int length,int x)//構造順序表     {         this->element=new int[length];         this->length=this->n=length;         if (int i=0;i<this->n;i++)         {             this->element[i]=x;         }     }     SeqList(int values[],int n )//構造順序表  由values提供元素  n為個數     {         this->init(values,n);     }     bool empty()//判斷順序表是否為空     {         return this->n==0;     }     int count()//返回順序表元素個數     {         return this->n;     }     void DispList()//輸出元素     {     cout << "Out:" << endl;     for(int i=0; i<length; i++){         cout << element[i] << " ";     }     cout << endl;     }     void insert(int i,T x)//在第i個元素插入     {         if(i<0)i=0;         if(i>this->n) i=this->n;         T*temp=this->element;         for(int j=this->n-1;j>=i;j--)             this->element[j+1]=temp[j];         if(temp!=this->element)             delete[]temp;         this->element[i]=x;         this->n++;     }     void insert(T x)//在末尾插入     {         insert(this->n,x);     }     int serch(T key,int str)//查詢     {         for(int i=str;i<this->n;i++)                      if(this->element[i]==key)                 return i;

        return -1;     }     int remove(int i)//刪除第i個元素     {         for(int j=i;j<this->n;j++)             this->element[j]=this->element[j+1];         return 0;     }          }; void main() {     SeqList <int> Seql;     int xy[10]={1,2,3,4,5,6,7,8,9,10     };     Seql.init(xy,10);     Seql.DispList();     Seql.insert(2,9);     Seql.DispList();     Seql.insert(10);     Seql.DispList();     cout<<Seql.serch(8,3)<<endl;     Seql.remove(4);     Seql.DispList();          

}