C++ 类模板实现容器

#include 
using namespace std; 

template
class vector
{
public:
	vector(int size = 10)	
	{	
		first = new T[size];
		last = first;		
		end = first + size;	
	}	
	~vector()	
	{
		delete[]first;		
		first = last = end = nullptr;	
	}	
	vector(const vector &src)//拷贝	
	{
		int size = src.end - src.first;		
		first = new T[size];		
		last = first;		
		for (T *p = src.first; p != src.last; ++p)		
		    {*last++ = *p;	}		
		end = first + size;	
	}	
	vector(vector &&src)	
	{	
		first = src.first;		
		last = src.last;		
		end = src.end;		
		src.first = src.last = src.end = nullptr;	
	}	
	void operator=(const vector &src)//赋值	
	{	
		if (this == &src) return; 		
		delete[]first; 		
		int size = src.end - src.first;		
		first = new T[size];		
		last = first;		
		for (T *p = src.first; p != src.last; ++p)		
		    {*last++ = *p;	}		
		    end = first + size;	
	}	  
        void operator=(vector &&src)	
        {	
        	delete[]first; 		
        	first = src.first;		
        	last = src.last;		
        	end = src.end;		
        	src.first = src.last = src.end = nullptr;	
        } 
        	
        void push_back(const T &val) // 末尾添加元素	
        {	
        	if (full())expand(); 		
        	*last++ = val;	
        }	
        
        void pop() // 删除末尾元素	
        {if (!empty())last--;	}	
        
        bool full()const	
        { return last == end;	}	
        
        bool empty()const	
        { return first == last;	}
        
private:	
        T *first; // 数组的起始地址	
        T *last;  // 数组最后一个有效元素的后继位置 	
        T *end;   // 数组最后一个元素的后继位置 	
        
        void expand() // 2倍扩容函数	
        {	
        	int size = end - first;		
        	T *s = new T[size * 2]; 		
        	for (int i = 0; i < size; i++)		
        	{
        	        s[i] = first[i];
        	} 		
        	first = s;		
        	delete[]s;		
        	last = first + size;		
        	end = first + size * 2;	
        }
};

 int main()
 {
 	 vectorintvec; 	
 	 return 0;
}

你可能感兴趣的:(代码)