c++ 实现 Vector

#include<iostream>         // 标准模板库当中Vector的简化版本
#include<vector>
using namespace std;

template<class t>
class array
{
public:
	array(int size);
	size_t getVectorSize()
	{
		return _data.size();
	}
	size_t getSize()
	{
		return _size;
	}
public:
	vector<t> _data;
	size_t _size;
};

template<class T>
class Vector
{
	T *start,*finish,*end;
public:
	Vector():start(0),finish(0),end(0){}
	void push_back(const T &x)
	{
		int size=finish-start;
		if(end-finish>0)
		{
			*finish=x;
			finish++;
		}
		else
		{
			if(size==0)
				size=1;
			T* newStart=(T*)operator new(2*size*sizeof(T));
			for(T *p=start,*q=newStart;p!=finish;p++,q++)
			{
				new (q) T(*p);
			}
			for(T *p=start;p!=finish;p++)
				p->~T();
			finish=newStart+(finish-start);
			end=newStart+2*size;
			if(start!=NULL)
			operator delete(start);
			start=newStart;
			new (finish) T(x);
			finish++;
		}
	}
	int size()
	{
		return finish-start;
	}
	T& operator[](size_t i)
	{
		return start[i];
	}
};

  

posted on 2013-08-18 10:06  dyc0113  阅读(194)  评论(0编辑  收藏  举报

导航