前言
今天在学习算法的时候,接触到了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++模板函数详解
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/93493.html