实现一个简单的vector
Vector基于数组实现,可以复制并且其占用的内存可以自动回收(通过析构函数),可以调整Vector的大小,以及容量(容量的改变是通过为基本数组分配一个新的内存块,然后复制旧的内存块到新块中,再释放旧块的内存)。在进行插入和删除操作时,需要位置标记,这里使用通用的迭代器(其实就是指针)。
代码如下:
/* * 用数组的方式实现线性表 */ #include<iostream> using namespace std; template <typename Object> class Vector { private: int theSize; int theCapacity; Object * objects; public: //构造函数 explicit Vector(int initSize = 0) : theSize(initSize), theCapacity(initSize + SPACE_CAPACITY) { objects = new Object[theCapacity]; } //拷贝构造函数 Vector(const Vector &rhs) :objects(NULL) { operator=(rhs); } //析构函数 ~Vector() { delete[] objects; } //重载复制操作符 const Vector &operator=(const Vector &rhs) { if (this != rhs) { delete[] objects; theSize = rhs.theSize; theCapacity = rhs.theCapacity; objects = new Object[capacity()]; for (int i = 0; i < size();++i) { objects[i] = rhs.objects[i]; } } return *this; } //调整Vector的大小 void resize(int newSize) { if (newSize > theCapacity) { reverse(newSize * 2 + 1); } theSize = newSize; } //调整容量 void reverse(int newCapacity) { if (newCapacity < theSize) return; Object *oldArray = objects; objects = new Object[newCapacity]; for (int i = 0; i < size(); ++i) { objects[i] = oldArray[i]; } theCapacity = newCapacity; delete[] oldArray; } //重载取元素操作符[] Object & operator[](int index) { return objects[index]; } //重载取元素操作符[] 返回值为左值不可修改 Object & operator[](int index) const { return objects[index]; } //判断是否为空 bool empty() { return theSize == 0; } //获得Vector的大小 int size() const { return theSize; } //获得theCapacity的大小 int capacity() const { return theCapacity; } //在尾部插入元素 void push_back(const Object &x) { if (theSize == theCapacity) { reverse(2 * theCapacity + 1); } objects[theSize++] = x; } //弹出尾部元素 void pop_back() { theSize--; } //返回尾部元素 const Object &back() const { return objects[theSize - 1]; } //使用指针定义迭代器 typedef Object * itreator; typedef const Object * const_itreator; //获取开始的迭代器 itreator begin() { return &objects[0]; } const_itreator begin() const { return &objects[0]; } //获取结束的迭代器 itreator end() { return &objects[size()]; } const_itreator end() const { return &objects[size()]; } enum { SPACE_CAPACITY = 16 }; }; int main() { Vector<int> vec; vec.push_back(2); vec.push_back(3); for (auto it = vec.begin(); it != vec.end();++it) { cout << *it << ' '; } return 0; }
输出: