C++---模拟实现vector

#include<iostream>
#include<assert.h>

typedef int DataType;

using namespace std;

class Vector
{
public:
	Vector()
		:_first(NULL)
		,_finish(NULL)
		,_endofstorage(NULL)
	{}
	Vector(const Vector &v)
	{
		if(v.Size() > 0)
		{
			_first  =  new DataType[v.Size()];
			memcpy(_first, v._first, sizeof(DataType)*(v.Size()));
			_finish = _first + v.Size();
			_endofstorage = _first + v.Size();
		}
		else
			_first = _finish = _endofstorage = NULL;
	}
	Vector& operator=(Vector v)
	{
		swap(_first, v._first);
		swap(_finish, v._finish);
		swap(_endofstroage, v._endofstorage);
		return *this;
	}
	~Vector()
	{
		delete[] _first;
		_first = _finish  = _endofstorage = NULL;
	}
	size_t Size() const
	{
		return _finish - _first;
	}
	size_t Capacity(size_t n)
	{
		return _endofstorage - _first;
	}
	void Expand(size_t  n)
	{
		if(n > Capacity() )
		{
			size_t size = Size();
			DataType *tmp = new DataType[n];
			if(_first)
			{
				memcpy(tmp, _first, sizeof(DataType)*Size());
				delete[] _first;
			}
			_first = tmp;
			_finish = _first + size;
			_endofstorage = _first + n; 
		}
	}
	void PushBack(DataType x)
	{
		if (_finish == _endofstorage)
		{
			if (Capacity() == 0)
				Expand(3);
			else
				Expand(Capacity() * 2);
		}
		*_finish = x;
		++_finish;
	}
	void Reserve(size_t n)
	{
		if (n > Capacity() )
			Expand(n);
	}
	void PopBack()
	{
		assert(_finish > _first);
		--_finish;
	}
	void Insert(size_t pos,DataType x)
	{
		assert(pos <= Size() );
		if (_finish == _endofstorage)
		{
			if (Capacity() == 0)
				Expand(3);
			else
				Expand(Capacity() * 2);
		}
		int end = Size() - 1;
		while (end >= (int)pos)
		{
			_first[end + 1] = _first[end];
			--end;
		}
		_first[pos] = x;
		++_finish;
	}
	void Erase(size_t pos)
	{
		assert (pos < Size() );
		size_t cur = pos;
		while( cur < Size() - 1)
		{
			_first[cur] = _first[cur + 1];
			++cur;
		}
		--_finish;
	}
	size_t Find(DataType x)
	{
		size_t cur=0;
		while(cur < Size() )
		{
			if(_first[cur]==x)
				return cur;
		}
		return -1;
	}
	void Print()
	{
		DataType *cur = _first;
		while (cur != _finish)
		{
			cout<< *cur<< " ";
			++cur;
		}
		cout << endl;
	}
private:
	DataType *_first;
	DataType *_finish;
	DataType *_endofstorage;
};

如果有什么不对的地方,可以评论告诉我,望指导!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值