码迷,mamicode.com
首页 > 其他好文 > 详细

vector容器的实现

时间:2014-10-07 15:15:53      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:blog   os   ar   for   2014   c   on   log   r   

简单实现了构造、析构、push_back、pop_back、operator=、operator[]、clear等函数

template<class T> 
class my_vector {
private:
	int count;
	int alloc_size;
	T *arr;
public:
	my_vector():count(0),alloc_size(0),arr(NULL)
	{
	}
	my_vector(int n, T ele): count(0),alloc_size(n)
	{
		arr = new T[n];
		while(n--)
		{
			push_back(ele);
		}
	}
	my_vector(const my_vector &other):count(0),alloc_size(0),arr(NULL)
	{
		*this = other;
	}

	my_vector<T>& operator=(const my_vector &other)
	{
		count = other.size();
		alloc_size = count;
		T *oldarr = arr;
		arr = new T[count];
		for(int i = 0; i < count; i++)
			arr[i] = other[i];
		delete []oldarr;
	}

	void push_back(T ele)
	{
		if(count == alloc_size)
		{
			T *oldarr = arr;
			int new_size;
			if(alloc_size == 0)
				new_size = 1;
			else
				new_size = alloc_size*2;

			arr = new T[new_size];
			for(int i = 0; i < count; i++)
			{
				arr[i] = oldarr[i];
			}
			alloc_size = new_size;
			delete []oldarr;
		}
		arr[count] = ele;
		count++;
	}

	void pop_back()
	{
		if(count > 0)
			count--;
	}

	int size()
	{
		return count;
	}

	T& operator[](int pos)
	{
		assert(pos < count);
		return arr[pos];
	}

	void clear()
	{
		count = 0;
	}

	~my_vector()
	{
		count = 0;
		alloc_size = 0;
		delete []arr;
		arr = NULL;
	}

};


vector容器的实现

标签:blog   os   ar   for   2014   c   on   log   r   

原文地址:http://blog.csdn.net/miao65272156/article/details/39852809

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!