面试:vector类的简单实现
vector类的简单实现
1 #include <vector> 2 #include <iostream> 3 #include <cstring> 4 #include <cassert> 5 using namespace std; 6 7 template<typename T> 8 class MyVector{ 9 private: 10 const size_t WALK_LENGTH = 16; 11 12 T* _array; 13 size_t _size; 14 size_t _capacity; 15 public: 16 MyVector():_array(nullptr),_size(0),_capacity(0){} 17 18 MyVector(size_t n,T value = 0){ 19 _capacity = WALK_LENGTH; 20 while(n > _capacity){ 21 _capacity += WALK_LENGTH; 22 } 23 _array = new T[_capacity]; 24 _size = n; 25 while(n--){ 26 _array[n] = value; 27 } 28 } 29 30 MyVector(const MyVector<T>& other){ 31 this->_size = other._size; 32 this->_capacity = other._size; 33 this->_array = new T[_capacity]; 34 memcpy(_array,other._array,sizeof(T)*_capacity); 35 } 36 37 ~MyVector(){ 38 if(this->_array){ 39 delete [] this->_array; 40 } 41 } 42 43 MyVector<T>& operator=(const MyVector& other){ 44 if(this == &other){ 45 return *this; 46 } 47 if(this->_array){ 48 delete [] _array; 49 } 50 this->_array = new T[other._capacity]; 51 this->_capacity = other._capacity; 52 this->_size = other._size; 53 memcpy(this->_array,other._array,_capacity*sizeof(T)); 54 return *this; 55 } 56 57 T operator[](size_t index){ 58 assert(index < this->_size); 59 return _array[index]; 60 } 61 62 size_t size(){ 63 return this->_size; 64 } 65 size_t capacity(){ 66 return this->_capacity; 67 } 68 bool isEmpty(){ 69 return this->_size == 0; 70 } 71 72 void push_back(const T& t){ 73 if(this->_size == this->_capacity){ 74 T* tmp = this->_array; 75 this->_array = new T[_capacity+WALK_LENGTH]; 76 memcpy(this->_array,tmp,this->_size*sizeof(T)); 77 this->_capacity += WALK_LENGTH; 78 delete [] tmp; 79 } 80 81 this->_size += 1; 82 _array[_size -1] = t; 83 } 84 85 void insert(size_t pos,const T& t){ 86 assert(pos <= _size); 87 88 if(_size == _capacity){ 89 _capacity += WALK_LENGTH; 90 T* tmp = _array; 91 _array = new T[_capacity]; 92 memcpy(_array,tmp,sizeof(T)*_size); 93 delete [] tmp; 94 } 95 for(size_t i = _size-1;i>=pos;i--){ 96 _array[i+1] = _array[i]; 97 } 98 _array[pos] = t; 99 _size += 1; 100 } 101 102 void erase(size_t pos){ 103 assert(pos < _size); 104 105 for(size_t i=pos+1;i<_size;i++){ 106 _array[i-1] = _array[i]; 107 } 108 _size--; 109 } 110 }; 111 112 113 int main(){ 114 MyVector<int> v(3); 115 v.push_back(4); 116 v.push_back(10); 117 v.insert(1,100); 118 v.erase(2); 119 std::cout << v[3] << std::endl; 120 std::cout << v.capacity() << std::endl; 121 std::cout << v.size() << std::endl; 122 for(size_t i=0;i<v.size();i++){ 123 std::cout << v[i] << ","; 124 } 125 std::cout << std::endl; 126 return 0; 127 }