qq_36573673 2017-05-26 11:14 采纳率: 0%

# c++写一个模板 Compare函数

• 写回答

#### 3条回答默认 最新

• 内核之道 PostgreSQL领域优质创作者 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;
}

``````
本回答被题主选为最佳回答 , 对您是否有帮助呢?
评论

#### 悬赏问题

• ¥20 Yolov5训练报错
• ¥15 Unity发布gzip压缩的webgl之后让浏览器可以正常显示画面
• ¥15 有没有人知道这种提示怎么关？现在不做ts项目了不知道咋关了，求解，现在我以前的js项目都是这种提示了
• ¥15 为什么mysql做了碎片化处理data_free还是很高
• ¥15 single positional indexer is out-of-bounds
• ¥15 LSTM 模型数据量需要多少？
• ¥15 mysql数据抓包开发报表
• ¥15 linux系统下安装office打不开
• ¥20 rsync脚本分发错误，文件不齐全
• ¥15 labview顺序结构与时间延时