qq_36573673
qq_36573673
采纳率60%
2017-05-26 11:14 阅读 2.6k

c++写一个模板 Compare函数

对int,char*,int *,double类型的两个数据进行比较

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

3条回答 默认 最新

  • 已采纳
    lixiaogang_theanswer 君子黎 2017-05-26 13:35
    模板:
    int Compare(T a, U b)
    {
        if (a>b)
        {
            return 1;
        }
       if (a == b)
        {
            return 0;
        }
       if (a < b) 
            return -1;
    }
    
    

    测试代码:

    #include<stdlib.h>
    #include<iostream>
    #include<string>
    #include<vector>
    using namespace std;
    
    
    
    template<class T,class U>
    int Compare(T a, U b)
    {
        if (a>b)
        {
            return 1;
        }
       if (a == b)
        {
            return 0;
        }
       if (a < b) 
            return -1;
    }
    
    void MInt()
    {
        int a = 3;
        int b = 5;
        if (Compare<int, int>(a, b) ==0)
            cout << "a == b" << endl;
        else if (Compare<int, int>(a, b) > 0)
        {
            cout << "a > b" << endl;
        }
        else if (Compare<int, int>(a, b) < 0) 
            cout << "a < b" << endl;
    }
    
    void MDouble()
    {
        double a = 4.0;
        double b = 5.0;
        if (Compare<double, double>(a, b) == 0)
            cout << "a == b" << endl;
        else if (Compare<double, double>(a, b) > 0)
        {
            cout << "a > b" << endl;
        }
        else if (Compare<double, double>(a, b) < 0)
            cout << "a < b" << endl;
    }
    
    void _MInt()
    {
        int * a = new int;
        *a = 3;
        int *b = new int;
        *b = 5;
        if (Compare<int*, int*>(a, b) == 0)
            cout << "a == b" << endl;
        else if (Compare<int*, int*>(a, b) > 0)
        {
            cout << "a > b" << endl;
        }
        else if (Compare<int*, int*>(a, b) < 0)
            cout << "a < b" << endl;
    }
    
    void _MDouble()
    {
        double *a = new double;
        *a = 3.0;
        double *b = new double;
        *b = 5.0;
        *b = 5;
        if (Compare<double*, double*>(a, b) == 0)
            cout << "a == b" << endl;
        else if (Compare<double*, double*>(a, b) > 0)
        {
            cout << "a > b" << endl;
        }
        else if (Compare<double*, double*>(a, b) < 0)
            cout << "a < b" << endl;
    
    }
    int main()
    {
        MInt();
        MDouble();
        _MInt();
        _MDouble();
        system("pause");
        return 0;
    }
    
    
    点赞 评论 复制链接分享
  • lixiaogang_theanswer 君子黎 2017-05-26 13:37
    模板那里写丢了模板声明,加上template<class T,class U>
    
    
    点赞 评论 复制链接分享
  • zhang_guyuan jalen_zh 2017-05-28 08:48

    template
    bool Compare(T1 t1,T2 t2)
    {
    if(t1>t2)
    return true;
    if(t1<t2)
    return false;
    }

    
    
    点赞 评论 复制链接分享

相关推荐