面试:vector类的简单实现

时间:2023-12-04 18:21:08

vector类的简单实现

 #include <vector>
#include <iostream>
#include <cstring>
#include <cassert>
using namespace std; template<typename T>
class MyVector{
private:
const size_t WALK_LENGTH = ; T* _array;
size_t _size;
size_t _capacity;
public:
MyVector():_array(nullptr),_size(),_capacity(){} MyVector(size_t n,T value = ){
_capacity = WALK_LENGTH;
while(n > _capacity){
_capacity += WALK_LENGTH;
}
_array = new T[_capacity];
_size = n;
while(n--){
_array[n] = value;
}
} MyVector(const MyVector<T>& other){
this->_size = other._size;
this->_capacity = other._size;
this->_array = new T[_capacity];
memcpy(_array,other._array,sizeof(T)*_capacity);
} ~MyVector(){
if(this->_array){
delete [] this->_array;
}
} MyVector<T>& operator=(const MyVector& other){
if(this == &other){
return *this;
}
if(this->_array){
delete [] _array;
}
this->_array = new T[other._capacity];
this->_capacity = other._capacity;
this->_size = other._size;
memcpy(this->_array,other._array,_capacity*sizeof(T));
return *this;
} T operator[](size_t index){
assert(index < this->_size);
return _array[index];
} size_t size(){
return this->_size;
}
size_t capacity(){
return this->_capacity;
}
bool isEmpty(){
return this->_size == ;
} void push_back(const T& t){
if(this->_size == this->_capacity){
T* tmp = this->_array;
this->_array = new T[_capacity+WALK_LENGTH];
memcpy(this->_array,tmp,this->_size*sizeof(T));
this->_capacity += WALK_LENGTH;
delete [] tmp;
} this->_size += ;
_array[_size -] = t;
} void insert(size_t pos,const T& t){
assert(pos <= _size); if(_size == _capacity){
_capacity += WALK_LENGTH;
T* tmp = _array;
_array = new T[_capacity];
memcpy(_array,tmp,sizeof(T)*_size);
delete [] tmp;
}
for(size_t i = _size-;i>=pos;i--){
_array[i+] = _array[i];
}
_array[pos] = t;
_size += ;
} void erase(size_t pos){
assert(pos < _size); for(size_t i=pos+;i<_size;i++){
_array[i-] = _array[i];
}
_size--;
}
}; int main(){
MyVector<int> v();
v.push_back();
v.push_back();
v.insert(,);
v.erase();
std::cout << v[] << std::endl;
std::cout << v.capacity() << std::endl;
std::cout << v.size() << std::endl;
for(size_t i=;i<v.size();i++){
std::cout << v[i] << ",";
}
std::cout << std::endl;
return ;
}