STL中vector的实现

  • Post author:
  • Post category:其他


参照数据结构与算法分析C++描述(Mark Allen Weiss)一书中的实例,给出vector的一个简单实现代码如下:

template <typename Object>
class Vector {
public:
	//构造函数
	explicit Vector(int initSize = 0) : theSize(initSize), theCapacity(initSize + SPARE_CAPACITY),
		objects(new Object[theCapacity]) { }
	//复制构造函数
	Vector(const Vector &rhs) {
		theSize = rhs.theSize;
		theCapacity = rhs.theCapacity;
		objects = new Object[capacity()];
		for(int k = 0; k < size(); k++)
			objects[k] = rhs.objects[k];
	}
	//赋值操作符
	Vector& operator=(const Vector &rhs) {
		if(this != &rhs) {
			delete [] objects;
			theSize = rhs.Size;
			theCapacity = rhs.Capacity;
			objects = new Object[capacity()];
			for(int k = 0; k < size(); k++)
				objects[k] = rhs.objects[k];
		}
		return *this;
	}
	//析构函数
	~Vector() {
		delete [] objects;
	}

	void resize(int newSize) {
		if(newSize > theCapacity) //当新的数目大于容量时,重新给数组分配内存
			reserve(2 * newSize + 1);
		theSize = newSize;
	}

	void reserve(init newCapacity) {
		if (newCapacity < theSize)
			return;
		Object *oldArray = objects;
		objects = new Object[newCapacity];
		for(int k = 0; k < theSize; ++k)
			object[k] = oldArray[k];
		theCapacity = newCapacity;
		delete [] oldArray;
	}

	//重载下标操作符
	Object& opetator[](int index) {
		return objects[index];
	}

	const Object& operator[](int index) const {
		return objects[index];
	}

	bool empty() const {
		return size() == 0;
	}

	int size() const {
		return theSize;
	}

	int capacity() const {
		return theCapacity;
	}

	void push_back(Object &x) {
		if (theSize == theCapacity)
			reserve(2 * theCapacity + 1);
		objects.[theSize++] = x;
	}

	void pop_back() {
		--theSize;
	}

	const Object& back() const {
		return objects[theSize - 1];
	}

	typedef Object* iterator;
	typedef const Object* const_iterator;

	iterator begin() {
		return &objects[0];
	}

	const_iterator begin() const {
		return &objects[0];
	}

	iterator end() {
		return &objects[size()];
	}

	const_iterator end() const {
		return &objects[size()];
	}

	enum { SPARE_CAPACITY = 16 };

private:
	int theSize;
	int theCapacity;
	Object *objects;
};



版权声明:本文为u010009320原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。