实验目的和要求:
1、理解模板的作用。
2、掌握函数模板的声明方法和模板函数的生成方法。
3、掌握类模板的声明方法和模板类的生成方法。
实验内容和要求:
-----3.1----
编写一求两个数的最大值的函数Max,要求用模板实现对任意数据类型数据都可应用该函数求取结果,在main()函数中分别用整型、实型、字符型数据进行测试。
#include<iostream>
using namespace std;
template<typename T>
T maxx(T t1,T t2)
{
return t1>t2?t1:t2;
}
int main()
{
cout<<maxx(1,2)<<endl;
cout<<maxx(1.5,3.5)<<endl;
cout<<maxx('a','e')<<endl;
return 0;
}
----3.2----
编写一冒泡排序的函数模板能够对不同类型的数据进行排序。
#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;
template<typename T>
void Sort(T arr[],int Size)
{
for(int i=0; i<Size-1; i++)
{
for(int j=0; j<Size-i-1; j++)
{
if(arr[j+1]<arr[j])//从小到大排序
{
T ptr=arr[j+1];
arr[j+1]=arr[j];
arr[j]=ptr;
}
}
}
}
int a[1005];
double b[1005];
char c[1005];
int main()
{
int t,n;
cin>>t;
while(t--)
{
cin>>n;
for(int i=0; i<n; i++)
cin>>a[i];
for(int i=0; i<n; i++)
cin>>b[i];
for(int i=0; i<n; i++)
cin>>c[i];
Sort(a,n);
for(int i=0; i<n; i++)
cout<<a[i]<<" ";
cout<<endl;
Sort(b,n);
for(int i=0; i<n; i++)
cout<<b[i]<<" ";
cout<<endl;
Sort(c,n);
for(int i=0; i<n; i++)
cout<<c[i]<<" ";
cout<<endl;
}
return 0;
}
/*
1
5
5 4 6 1 8
1.2 0.8 2.2 3.5 0.1
kjfhd
*/
----3.3----
试编写一个栈的类模板(包括其成员函数的定义),以便为任何类型的对象提供栈结构数据的操作,操作至少包括:
入栈和出栈操作。
#include<iostream>
using namespace std;
const int Size=100;
template<typename T>
class Stack
{
public:
void init()
{
tot=0;
}
void push(T ch);
T pop();
private:
T stck[Size];
int tot;
};
template<class T>
void Stack<T>::push(T ob)
{
if(tot==Size)
{
cout<<"Stack is full"<<endl;
return;
}
stck[tot++]=ob;
}
template<class T>
T Stack<T>::pop()
{
if(tot==0)
{
cout<<"Stack is empty"<<endl;
return 0;
}
return stck[--tot];
}
int main()
{
Stack <char> s1,s2;
s1.init();
s2.init();
s1.push('a');
s2.push('x');
s1.push('b');
s2.push('y');
s1.push('c');
s2.push('z');
for(int i=0; i<3; i++)
cout<<s1.pop()<<" ";
cout<<endl;
for(int i=0; i<3; i++)
cout<<s2.pop()<<" ";
cout<<endl;
Stack<int>is1,is2;
is1.init();
is2.init();
is1.push(1);
is2.push(2);
is1.push(3);
is2.push(4);
is1.push(5);
is2.push(6);
for(int i=0; i<3; i++)
cout<<is1.pop()<<" ";
cout<<endl;
for(int i=0; i<3; i++)
cout<<is2.pop()<<" ";
cout<<endl;
return 0;
}