vector(int size = 0, T def = T());
vector(const vector& other);
unsigned int size();
T& operator[](unsigned int ind);
void clear();
void erase(unsigned int start, unsigned int end);
void erase(unsigned int ind);
void push_back(T ind);
void pop_back();
T front();
T back();
vector& operator=(const vector& other);
~vector();
实现基本功能,具有基本的数据内存管理功能,能适配各种数据类型。
缺点是没实现迭代器, 因此不支持sort等stl算法。
vector.hpp
#include<cstdlib>
#include<cstring>
#include<cassert>
template <typename T>
class vector {
public:
vector(int size = 0, T def = T());
vector(const vector& other);
unsigned int size();
T& operator[](unsigned int ind);
void clear();
void erase(unsigned int start, unsigned int end);
void erase(unsigned int ind);
void push_back(T ind);
void pop_back();
T front();
T back();
vector& operator=(const vector& other);
~vector();
private:
int* arr = NULL;
unsigned int _size;
unsigned int capcity = 0;
};
template<typename T>
inline vector<T>::vector(int size, T def)
{
capcity = 2 * size + 1;
arr = new T[capcity];
this -> _size = size;
for (unsigned int i = 0; i < size; i++) {
arr[i] = def;
}
}
template<typename T>
inline vector<T>::vector(const vector& other)
{
this->clear();
arr = new T[other.capcity];
this->capcity = other.capcity;
this->_size = other._size;
memmove(this->arr, other.arr, capcity * sizeof(T));
return;
}
template<typename T>
inline unsigned int vector<T>::size()
{
return _size;
}
template<typename T>
inline T& vector<T>::operator[](unsigned int ind)
{
assert(ind < _size);
return arr[ind];
}
template<typename T>
inline void vector<T>::clear()
{
delete[] arr;
arr = NULL;
_size = 0;
capcity = 0;
return;
}
template<typename T>
inline void vector<T>::erase(unsigned int start, unsigned int end)
{
assert(start < end || (start >= 0 && start < _size) || (end >= 0 && end < _size));
unsigned len = end - start + 1;
memmove(arr + start, arr + end + 1, sizeof(T)*(_size - end));
_size -= len;
return;
}
template<typename T>
inline void vector<T>::erase(unsigned int ind)
{
erase(ind, ind);
return;
}
template<typename T>
inline void vector<T>::push_back(T ind)
{
T* new_arr = NULL;
if (_size >= capcity) {
new_arr = new T[2 * _size + 1];
memmove(new_arr, arr, _size * sizeof(T));
T* temp = arr;
delete[] temp;
arr = new_arr;
capcity = 2 * _size + 1;
}
arr[_size++] = ind;
return;
}
template<typename T>
inline void vector<T>::pop_back()
{
if (_size == 0) return;
arr[_size--].~T();
return;
}
template<typename T>
inline T vector<T>::front()
{
if (_size == 0) return T();
return arr[0];
}
template<typename T>
inline T vector<T>::back()
{
if (_size == 0) return T();
return arr[_size-1];
}
template<typename T>
inline vector<T>& vector<T>::operator=(const vector& other)
{
this->clear();
arr = new T[other.capcity];
this->capcity = other.capcity;
this->_size = other._size;
memmove(this->arr, other.arr, capcity * sizeof(T));
return *this;
}
template<typename T>
inline vector<T>::~vector()
{
delete[] arr;
return;
}