MyArrayList类实现代码
1 #pragma once 2 3 template<class T> 4 class MyArrayList 5 { 6 public: 7 8 int Length; //list中已有的元素的个数 9 10 MyArrayList(void) 11 { 12 Length = 0; 13 size = 10; 14 index = 0; 15 list = new T [10]; 16 } 17 18 MyArrayList(int Size) 19 { 20 if(Size<0) 21 Size=10; 22 Length = 0; 23 size = Size; 24 index = 0; 25 list = new T [Size]; 26 } 27 28 //添加元素 29 void Add(T value) 30 { 31 EnsureCapacity(index+1); 32 list[index] = value; 33 index++; 34 Length = index; 35 } 36 37 //自动增长,确保添加元素时不会越界 38 void EnsureCapacity(int paramInt) 39 { 40 if(paramInt>=size) 41 { 42 T *newlist = new T [size*3/2+1]; 43 Copy(list,newlist); 44 delete list; 45 list = newlist; 46 size = size*3/2+1; 47 } 48 } 49 50 //按照索引获取元素 51 T Get(int paramInt) 52 { 53 return list[paramInt]; 54 } 55 56 //按照索引删除元素 57 void Remove(int paramInt) 58 { 59 paramInt= paramInt-1; 60 for(int i=paramInt;i<Length;i++) 61 { 62 list[i]=list[i+1]; 63 } 64 list[Length-1]=0; 65 Length=Length-1; 66 } 67 68 void Remove(T paramObject,int x) 69 { 70 for(int i=0;i<Length;i++) 71 { 72 if(list[i]==paramObject) 73 Remove(i+1); 74 } 75 } 76 77 T * GetList() 78 { 79 return list; 80 } 81 82 ~MyArrayList(void) 83 { 84 delete list; 85 } 86 87 private: 88 89 int size; //list总长度 90 int index; //最后一个元素索引值 91 T *list; 92 93 void Copy(T * oldArray,T * newArray) 94 { 95 for(int i=0;i<size;i++) 96 { 97 newArray[i] = oldArray[i]; 98 } 99 } 100 101 };
测试代码:
1 MyArrayList<int> *list = new MyArrayList<int>(); 2 3 list->Add(6);list->Add(7);list->Add(3);list->Add(8);list->Add(9);list->Add(5);list->Add(0); 4 list->Add(2);list->Add(1);list->Add(4);list->Add(14);list->Add(11);list->Add(12);list->Add(10); 5 6 std::cout<<"原数组 : "; 7 for(int i=0;i<list->Length;i++) 8 { std::cout<<list->Get(i)<<" ";} 9 std::cout<<std::endl; 10 11 list->Remove(9,0); 12 std::cout<<std::endl; 13 14 for(int i=0;i<list->Length;i++) 15 { std::cout<<list->Get(i)<<" ";}