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

vector容器的实现

时间:2017-06-11 10:04:51      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:oid   for   null   article   template   析构   []   back   private   

简单实现了构造、析构、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容器的实现

标签:oid   for   null   article   template   析构   []   back   private   

原文地址:http://www.cnblogs.com/clnchanpin/p/6984264.html

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