实验目的和要求
1.能够使用C++模板机制定义重载函数。
2.能够实例化及使用模板函数。
3.能够实例化和使用模板类。
4.应用标准C++模板库(STL)通用算法和函数对象实现查找和排序。
实验内容
1.分析并调试下列程序,了解函数模板的使用。
//sy8_1.cpp
include
using namespace std;
template
T max(T a,T b)
{
return a>b?a:b;
}
int main()
{
cout<<”max(6,5)is”<
include
using namespace std;
template
T max(T a,T b)
{
return a>b?a:b;}
char* max(char *a,char *b)
{return strcmp(a,b)>0? a:b;}
int main( ){
cout<<”max(6,5) is “<
include
include
template
class MySort
{
public:
MySort(T _stores[10])
{
stores = _stores;
}
void DoSort(bool up = true)
{
for(int i = 0; i < 10; i++)
{
for(int j = i+1; j < 10; j++)
{
if(up)//升序
{
if(stores[i] > stores[j])
{
T temp = stores[i];
stores[i] = stores[j];
stores[j] = temp;
}
}
else//降序
{
if(stores[i] < stores[j])
{
T temp = stores[i];
stores[i] = stores[j];
stores[j] = temp;
}
}
}
}
}
private:
T *stores;
};
int main()
{
//int
int nums[10] = { 1, 3, 2, 9, 7, 6, 8, 10, 4, 5};
MySort mySort(nums);
mySort.DoSort(true);//升序
for(int i = 0; i < 10; i++)
printf(“%d “, nums[i]);
printf(“\n”);
//float
float nums1[10] = { 99.7f, 99.1f, 81.2f, 1.1f, 2.2f, 7.7f, 7.8f, 49.1f, 75.3f, 89.99f};
MySort mySort1(nums1);
mySort1.DoSort(false);
for(int i = 0; i < 10; i++)
printf(“%0.2f “, nums1[i]);
printf(“\n”);
// char
char chars[10] = {‘a’, ‘A’, ‘B’, ‘b’, ‘z’, ‘X’, ‘W’, ‘e’, ‘g’, ‘H’};
MySort mySort2(chars);
mySort2.DoSort();
for(int i = 0; i < 10; i++)
printf(“%c “, chars[i]);
printf(“\n”);
return 0;
}
程序输出结果入下: