看一下简易实现的vector
#ifndef VECTOR_H
#define VECTOR_H
#include <iostream>
using namespace std;
template<class T>
class Vector
{
private:
int theSize;
int theCapacity;
T *objects;
public:
typedef T* iterator;
typedef const T* const_iterator;
enum{ SPARE_CAPACITY = 16 };
public:
explicit Vector(int initSize = 0); //用explicit避免隐式类型转换
~Vector();
Vector(const Vector<T>& rhs);
const Vector<T>& operator=(const Vector<T>& rhs);
void resize(int newSize);
void reserve(int newCapacity);
T& operator[](int index);
const T& operator[](int index) const;
bool empty() const;
int size() const;
int capacity() const;
void push_back(const T& x);
void pop_back();
const T& back() const;
iterator begin();
const_iterator begin() const;
iterator end();
const_iterator end() const;
};
template<class T>
Vector<T>::Vector(int initSize = 0) : theSize(initSize), theCapacity(initSize + SPARE_CAPACITY)
{
objects = new T[theCapacity];
}
template<class T>
Vector<T>::~Vector()
{
delete []objects;
}
template<class T>
Vector<T>::Vector(const Vector<T>& rhs) : objects(nullptr)
{
operator = (rhs);
}
template<class T>
const Vector<T>& Vector<T>::operator=(const Vector<T>& rhs)
{
if (this != &rhs)
{
delete[]objects;
theSize = rhs.size();
theCapcity = rhs.theCapacity;
// 注意是深拷贝
objects = new T[capacity()];
for (int k = 0; k < size(); k++)
objects[k] = rhs.objects[k];
}
return *this;
}
template<class T>
void Vector<T>::resize(int newSize)
{
if (newSize > theCapacity)
reserve(newSize * 2 + 1); //每次空间不够的时候,就重新获得2倍于当前容量的空间,+1是为了防止0的情况
theSize = newSize;
}
template<class T>
void Vector<T>::reserve(int newCapacity)
{
if (newCapacity < theSize)
return;
T *oldArray = objects;
// 之所以需要将老的数组复制到新的数组,是因为要保证Vector整块内存的连续性
objects = new T[newCapacity];
for (int k = 0; k < theSize; k++)
objects[k] = oldArray[k];
theCapacity = newCapacity;
delete []oldArray;
}
template<class T>
T& Vector<T>::operator[](int index)
{
return objects[index];
}
template<class T>
const T& Vector<T>::operator[](int index) const
{
return objects[index];
}
template<class T>
bool Vector<T>::empty() const
{
return size() == 0;
}
template<class T>
int Vector<T>::size() const
{
return theSize;
}
template<class T>
int Vector<T>::capacity() const
{
return theCapacity;
}
template<class T>
void Vector<T>::push_back(const T& x)
{
if (theSize == theCapacity)
reserve(theCapacity * 2 + 1);
objects[theSize++] = x;
}
template<class T>
void Vector<T>::pop_back()
{
theSize--;
}
template<class T>
const T& Vector<T>::back() const
{
return objects[theSize - 1];
}
template<class T>
T* Vector<T>::begin()
{
return &objects[0];
}
template<class T>
const T* Vector<T>::begin() const
{
return &objects[0];
}
template<class T>
T* Vector<T>::end()
{
return &objects[size() - 1];
}
template<class T>
const T* Vector<T>::end() const
{
return &objects[size() - 1];
}
#endif