STL库中vector的模拟

来源:互联网 发布:linux系统各种下载 编辑:程序博客网 时间:2024/03/28 20:51

  数据结构和算法分析C++描述中作者对STL中vector进行了模拟,实现了vector的简单功能,好东西不能独享,代码奉上

#ifndef VECTOR_H#define VECTOR_H#include "dsexceptions.h"template <typename T>class Vector{public:explicit Vector(int size = 0) : theSize(size),theCapacity(theSize + SPARE_CAPACITY){objects = new T [theCapacity];}Vector(const Vector<T > &rhs) : objects(nullptr){operator=(rhs);}~Vector(){delete []objects;}int size() const{return theSize;}int capacity() const{return theCapacity;}bool empty() const{return size() == 0;}T  & operator[](int index){if(index < 0 || index >= size()){throw ArrayIndexOutOfBoundsException();}return objects[index];}const T  & operator[](int index) const{if(index < 0 || index >= size()){throw ArrayIndexOutOfBoundsException();}return objects[index];}const Vector<T> & operator= (const Vector<T> &rhs){if(this != rhs){delete []objects;this->thesize = rhs.size();this->theCapacity = rhs.capacity();objects = new T [this->theCapacity];for(int i = 0; i < this->theSize; i++){objects[i] = rhs.objects[i];}}return *this;}void reserve(int newCapacity) //实现数组容量的调整{T  *oldObjects = objects;int numCopy = 0;if(newCapacity < this->capacity()){numCopy = newCapacity;}else{numCopy = this->size();}newCapacity += SPARE_CAPACITY;T * newObjects = new T [newCapacity];for(int i = 0; i < numCopy; i++) //拷贝原来的数据{newObjects[i] = objects[i];}delete []oldObjects;objects = newObjects;this->theSize = numCopy;this->theCapacity = newCapacity;}void resize( int newSize ){if( newSize > theCapacity )reserve( newSize * 2 );theSize = newSize;}void push_back(T  &value)//Vector尾部加入1个元素{if( theSize == theCapacity ){reserve( 2 * theCapacity + 1 );//数组容量自动增长}objects[theSize++] = value;}void pop_back() //删除Vector尾部元素{if(theSize < 0){throw UnderflowException();}theSize--;//thsSize减下去,刚才的元素在无法被引用了,成为了孤儿,这片内存泄露了吗?}const T  & back() //取出尾部元素,Vector不变化{if(theSize < 0){throw UnderflowException();}return objects[theSize-1];}//模拟STL中的iteratortypedef T * iterator;typedef const T * const_iterator;iterator begin(){return &objects[0];}const_iterator cbegin(){return &objects[0];}iterator end(){return &objects[size()];}const_iterator cend(){return &objects[size()];}enum { SPARE_CAPACITY = 16 };private:int theSize;int theCapacity;T  *objects;};#endif

测试方法:

#include <iostream>#include "Vector.h"using std::cin;using std::cout;using std::endl;int main(){Vector<int> vec;for(int i = 0; i < 100; i++){vec.push_back(i);}cout << "size=" << vec.size() << endl;cout << "capacity=" << vec.capacity() << endl;vec[0] = 555;for(int i = 0; i < vec.size(); i++){cout << "," << vec[i];}cout << endl;vec.pop_back();for(int i = 0; i < vec.size(); i++){cout << "," << vec[i];}cout << endl;Vector<int>::iterator iter = vec.begin();cout << "*iter=" << *iter;system("pause");return 0;}


0 0
原创粉丝点击