C++ 类模板实现容器

本文深入探讨了如何使用C++的类模板来实现自定义的容器,包括模板的基本概念、类模板的定义与实例化,以及如何利用模板实现类似std::vector和std::map的功能。通过实例代码,详细解释了模板参数、类型推断和模板特化等关键概念,帮助读者掌握C++中构建高效、泛型的容器技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
using namespace std; 

template<typename T>
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<T> &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<T> &&src)	
	{	
		first = src.first;		
		last = src.last;		
		end = src.end;		
		src.first = src.last = src.end = nullptr;	
	}	
	void operator=(const vector<T> &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<T> &&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()
 {
 	 vector<int>intvec; 	
 	 return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值