模板——函数模板&类模板

模板主要是针对数据类型,不同的数据类型却具有相同的操作形式,比如说,同样是做入栈,intdouble由于数据类型不一样,需要做两个栈才能满足需求,诚然可以使用函数重载,但是终归栈的操作是一样的,只是数据类型不一样。所以在此基础上,假设,我们首先将所有的数据类型视为一个大类,将它参数化,等到要用的时候再去调用具体的类型,那么可以大大减少代码量,也使代码更清晰。
模板——也就是由上面的问题所引出来的解决机制。将相类似的问题抽象出共同的结构,不同的地方用参数来表达。
模板的具体表达为:template <class T>template <typename T>T代表数据类型。

  1. 函数模板
函数模板——>函数模板实例

重载函数可以抽象成一个模板,形同的操作保留,不同的操作(一般是数据类型)做成参数。
函数模板来定义排序或者输出。

template <class ElementType>
void sortArray (ElementType b[], int len){
	for (int i = 0; i < len - 1; i++)
		int min = i;
	for (int j = i+1; j < len; j++){
		if (b[j]<b[min])
			min = j;
	}
	 ElementType temp = b[i];
	 b[i] = b[min];
	 b[min] = temp;
}
template <class ElementType>
void displayArray (ElementType b[], int len){
	for (int k = 0; k < len; k++)
		cout << b[k];
	cout << endl;
}

以上是将数据类型参数化为template <class>,实例化后可以具体实现具体数据类型的数组的排序和输出。
1.1 函数模板实例化

# define SIZE 8
int main(){
	int ai[SIZE] = {18,35,8,89,54,68,32,74};
	double af[SIZE] = {1.21,52.3,54.9,4.5,85.7,96.4,87.0,6.5};
	dispalyArray(ai, SIZE);
	sortArray(ai, SIZE);
	dispalyArray(ai, SIZE);
	
	dispalyArray(af, SIZE);
	sortArray(af, SIZE);
	dispalyArray(af, SIZE);	
	
	return 0;
}

具体实行是,mian函数执行到dispalyArray(ai, SIZE);,将ai替换为template 的所有 ElementType类型。如果需要修改排序算法,只需要修改模板里的就可以了。

  1. 类模板
类模板——>类模板实例——>对象
#define DEFAULT_ELEM_NUM 8
template <class ElementType>
class Stack{
public:
	Stack (int DEFAULT_ELEM_NUM);
	~Stack() {delete [] data;};
	int pop (ElementType &num);
	int push (ElementType num);
private:
	ElementType *data;
	int memNum;
	int size;
};

template <class ElementType>
Stack<ElementType> :: Stack(int s){
	size = s>0 ? s : DEFAULT_ELEM_NUM; 
	data = new ElementType[s];
	memNum = 0;
}

template <class ElementType>
int Stack<ElementType> :: pop(ElementType &num){
	if (memNum == 0)
		return 0;
	num = data[--memNum];
	return 1;
}

template <class ElementType>
int Stack<ElementType> :: push(ElementType mem){
	if (memNum == size)
		reutrn 0;
	data[memNum++] = mem;
	retuen 1;
}

2.1 类模板实例化和对象实例化

int main(){
	//类模板实例化和对象实例化
	Stack<double> doubleStack(6);
	double f = 3.14;
	while (doubleStack.push(f)){
		cout << f << '';
		f += f;
	}
	while (doubleStack.pop(f))
		cout << f << '';
	
	return 0}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值