C++ 上机实验(三)【模板】

实验目的和要求:

1、理解模板的作用。

2、掌握函数模板的声明方法和模板函数的生成方法。

3、掌握类模板的声明方法和模板类的生成方法。


实验内容和要求:

-----3.1----
编写一求两个数的最大值的函数Max,要求用模板实现对任意数据类型数据都可应用该函数求取结果,在main()函数中分别用整型、实型、字符型数据进行测试。

#include
using namespace std;
template
T maxx(T t1,T t2)
{
    return t1>t2?t1:t2;
}
int main()
{
    cout<

----3.2----
编写一冒泡排序的函数模板能够对不同类型的数据进行排序。

#include
#include
#include
using namespace std;
template
void Sort(T arr[],int Size)
{
    for(int i=0; i>t;
    while(t--)
    {
        cin>>n;
        for(int i=0; i>a[i];
        for(int i=0; i>b[i];
        for(int i=0; i>c[i];
        Sort(a,n);
        for(int i=0; i


----3.3----
试编写一个栈的类模板(包括其成员函数的定义),以便为任何类型的对象提供栈结构数据的操作,操作至少包括:
入栈和出栈操作。

#include
using namespace std;
const int Size=100;
template
class Stack
{
public:
    void init()
    {
        tot=0;
    }
    void push(T ch);
    T pop();
private:
    T stck[Size];
    int tot;
};
template
void Stack::push(T ob)
{
    if(tot==Size)
    {
        cout<<"Stack is full"<
T Stack::pop()
{
    if(tot==0)
    {
        cout<<"Stack is empty"< 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<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<


你可能感兴趣的:(C++)