首页 > 代码库 > vector容器的实现

vector容器的实现

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