欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C++模拟实现vector

程序员文章站 2022-03-23 14:00:27
...

代码如下:

#include<iostream>
#include<string>
using namespace std;
template<class T>
class Vector
{
public:
	typedef T* itreator;//正向可修改迭代器
	typedef const T* const_itreator;//正向不可修改迭代器
	Vector()
		:_start(nullptr)
		, _finish(nullptr)
		, _endOfStorage(nullptr)
	{}
	itreator begin()
	{
		return _start;
	}
	itreator end()
	{
		return _finish;
	}
	const_itreator begin() const
	{
		return _start;
	}
	const_itreator end() const
	{
		return _finish;
	}
	size_t size()//获取当前有效元素个数
	{
		return _finish - _start;
	}
	size_t capacity()//获取当前容量
	{
		return _endOfStorage - _start;
	}
	void pushback(const T& val)//pushback的尾插
	{
		//先检查容量
		if (_finish == _endOfStorage)//需要扩容
		{
			size_t newC = capacity() == 0 ? 1 : 2 * capacity();
			reserve(newC);
		}
		*_finish = val;
		_finish++;
	}
	void reserve(size_t n)//reserve扩容
	{
		if (n > capacity())
		{
			int sz = size();
			T *tmp = new T[n];
			if (_start != nullptr)
			{
				for (int i = 0; i < sz; i++)//深拷贝,如果用memcpy是一个浅拷贝,会导致二次释放问题
				{
					tmp[i] = _start[i];
				}
				//delete[] _start;
			}
			_start = tmp;
			_finish = _start + sz;
			_endOfStorage = _start + n;
		}
	}
	T& operator[](size_t pos)
	{
		return _start[pos];
	}
	void resize(size_t n,const T& val)
	{
		if (n > capacity())
		{
			reserve(n);
		}
		if (n > size())
		{
			while (_finish != _start + n)
			{
				*_finish = val;
				++_finish;
			}
		}
		_finish = _start + n;
	}
	void insert(itreator pos, const T& val)//insrt插入
	{
		if (pos >= _start && pos <= _finish)
		{
			if (_finish == _endOfStorage)
			{
				int len = pos - _start;
				size_t newC = capacity() == 0 ? 1 : 2 * capacity();
				reserve(newC);
				pos = _start + len;
			}
			itreator end = _finish;
			while (pos != end)
			{
				*end = *(end - 1);
				end--;
			}
			*pos = val;
			_finish++;
		}
	}
	iterator erase(iterator pos)//删除迭代器指向的pos位置
	{
		if (pos >= begin() && pos < end())
		{
			iterator begin = pos + 1;
			while (begin != _finish)
			{
				*(begin - 1) = *begin;
				begin++;
			}
			--_finish;
			return pos;
		}
	}
	void pop_back()//尾删
	{
		if (size() > 0)
		{
			erase(end() - 1);
		}
	}
	Vector(const Vector<T>& v)//Vector泛型拷贝构造
		:_start(new T[capacity()])
		, _finish(_start + v.size())
		, _endOfStorage(_start + v.capacity());
	{
		//进行深拷贝
		for (int i = 0; i < v.size(); i++)
		{
			_start[i] = v[i];
		}
	}
	Vector<T>& operator=(Vector<T> v)
	{
		Swap(v);
		return *this;
	}
	void Swap(Vector<T>& v)
	{
		swap(_start, v._start);
		swap(_finish, v._finish);
		swap(_endOfStorage, v.endOfStorage);
	}
private:
	T *_start;
	T *_finish;
	T *_endOfStorage;
};
int main()
{
	system("pause");
	return 0;
}