C++ 模板函数

前言

今天在学习算法的时候,接触到了C++模板函数的概念,顺便练习整理一下知识点

模板函数

模板函数声明语句: template <typename T> 函数参数中具体的数据类型可由统一模板T代替

(模板名习惯上设置为T,可自定义)

案例

定义一个选择排序的模板,分别对不同类型的数组进行排序并输出

(其中整型数组为随机数组成的数组,省去手动输入测试)

随机生成数详解 C++中引入<ctime>库函数,这一点与C不同,其它的原理一致。

代码块

//定义模板函数 
template <typename T>
void SelectSort(T a[],int n){
	for(int i=0;i<n;i++){
		int min_index=i;
		for(int j=i+1;j<n;j++)
			if(a[j]<a[min_index])
			  min_index=j;
		swap(a[i],a[min_index]);	
	}
}

测试

#include<iostream>
#include<algorithm>
#include<ctime> 
using namespace std;
/*
1.自动生成一个随机数组
2.对其进行选择排序
3.使用模板函数进行不同类型数据的排序
如:整型,浮点型,字符型,结构体类型(自定义) 
*/ 
//定义模板函数 
template <typename T>
void SelectSort(T a[],int n){
	for(int i=0;i<n;i++){
		int min_index=i;
		for(int j=i+1;j<n;j++)
			if(a[j]<a[min_index])
			  min_index=j;
		swap(a[i],a[min_index]);	
	}
}

template <typename P>
void PrintArray(P a[],int n){
	for(int i=0;i<n;i++){
		cout<<a[i]<<" ";
	}
	cout<<endl;
}
//随机数组 
int* RandomArray(int n,int rangeL,int rangeR){
	int *arr=new int[n];//创建一个大小为n的数组 
	srand(time(NULL));//以时间为"种子"产生随机数 
	for(int i=0;i<n;i++){
		arr[i]=rand()%(rangeR-rangeL+1)+rangeL;//生成指定区间[rangeL,rangeR]里的数 
	}
	return arr;
}

int main(){
	float b[5]={0.5,2.7,1.5,15.8,10.2};
	char c[5]={'e','a','c','d','b'};
	int n;
	cout<<"请输入数据规模n:";cin>>n;
	int* a=RandomArray(n,1,100);//生成[1,100]内的随机数组成的数组 
	cout<<"整型排序:";SelectSort(a,n); PrintArray(a,n);//整型
	cout<<"浮点型排序:";SelectSort(b,5); PrintArray(b,5);//浮点型
	cout<<"字符型排序:";SelectSort(c,5); PrintArray(c,5);//字符型 
	return 0;
} 

 对于模板函数,我只是简略整理下(知道有这个东西,会用就行),更具体的知识点与用法还得看这位大佬的博客。C++模板函数详解

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Aricl.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值