用C++实现STL容器vector

来源:互联网 发布:光纤分布数据接口fddi 编辑:程序博客网 时间:2024/06/04 18:52
template<class Object>class Vector{public:enum {SPARE_CAPACITY = 16};explicit Vector(int initsize = 0):theSize(initsize), theCapacity(initsize + SPARE_CAPACITY){objects = new Object[theCapacity];}Vector(const Vector & rhs):objects(NULL){operator=(rhs);}~Vector(){delete [] objects;}const Vector & operator=(const Object &rhs){if (this != &rhs){delete [] objects;theSize = rhs.size();theCapacity = rhs.capacity();objects = new Object[capacity()];for (int i = 0; i < size(); i++){objects[i] = rhs.objects[i];}}return *this;}void resize(int newSize) {if (newSize > theCapacity)reserve(2 * newSize + 1);theSize = newSize;}void reserve(int capacity){if (capacity < theCapacity)return;Object *oldobject = objects;objects = new Object[capacity];for (int i = 0; i < theSize; i++)objects[i] = oldobject[i];theCapacity = capacity;delete [] oldobject;}int capacity()const{return theCapacity;}int size() const{return theSize;}Object & operator[](int index){return objects[index];}const Object & operator[](int index) const{return objects[index];}bool empty() const{return theSize == 0;}void push_back(const Object & ob){if (theSize == theCapacity)reserve(2 * theCapacity + 1);objects[theSize++] = ob;}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()];}private:int theSize;int theCapacity;Object *objects;};


#include <iostream>#include "Vector.h"using namespace std;//输出数组内容template<class Object>void print(Object  & obj){for (auto it = obj.begin(); it != obj.end(); it++)cout << *it << " ";cout << endl;}int main(){Vector<int> v;v.push_back(1);v.push_back(2);v.push_back(3);v.push_back(4);cout << "V: ";for (auto it = v.begin(); it != v.end(); it++)cout << *it << " ";cout << endl;cout << "V: ";print(v);v.pop_back();cout << "V: ";print(v);cout << "the size is " << v.size() << endl;cout << "the capacity is " << v.capacity() << endl;cout << "the back element is " << v.back() << endl;if (v.empty())cout << "the vector is empty.\n";elsecout << "the vector is not empty.\n";system("pause");exit(0);}


0 0