405b.cpp
来自「C++实训教程」· C++ 代码 · 共 92 行
CPP
92 行
/*
405b.cpp templateSwapSort
Written By S.Y.Feng
DEMO implement Sort() and Swap() of functions
by using function template
*/
#include <iostream.h>
#include <iomanip.h>
template <class T> void Swap(T& a,T& b);
template <class T> void Sort(T* pT,const int n);
main(void)
{
const int SIZE = 24;
int n[SIZE] ;
float f[SIZE];
int j;
//↓设置数据
for (j = 0; j < SIZE; j++)
{
n[j] = j * j - 4*j + 10;
f[j] = j * j - 4.5*j + 8.5;
}
cout << "Display data before Sort : \n" ;
cout << "int array are : " << endl;
for (j = 0; j < SIZE; j++)
{
cout << setw(8)<< n[j] ;
if(!((j+1) % 8)) cout << endl;
}
cout << "float array are : " << endl;
for (j = 0; j < SIZE; j++)
{
cout << setw(8)<< f[j] ;
if(!((j+1) % 8)) cout << endl;
}
//↓调用排序函数
Sort(n,SIZE );
Sort(f,SIZE );
cout << "Display data after Sort : \n" ;
cout << "int array are : " << endl;
for (j = 0; j < SIZE; j++)
{
cout << setw(8)<< n[j] ;
if(!((j+1) % 8)) cout << endl;
}
cout << "float array are : " << endl;
for (j = 0; j < SIZE; j++)
{
cout << setw(8)<< f[j] ;
if(!((j+1) % 8)) cout << endl;
}
return 0;
}
//↓函数模板Sort()的定义
template <class T>
void Sort(T* pT,const int n)
{
for (int m = n/2; m>0; m/=2)
for (int i = m; i<n; i++)
for (int j = i-m; j >=0 && pT[j+m] < pT[j];j -= m )
Swap(pT[j],pT[j+m]);
}
template <class T>
void Swap(T& a,T& b)
{
T temp(a);
a = b;
b = temp;
}
/*
Display data before Sort :
int array are :
10 7 6 7 10 15 22 31
42 55 70 87 106 127 150 175
202 231 262 295 330 367 406 447
float array are :
8.5 5 3.5 4 6.5 11 17.5 26
36.5 49 63.5 80 98.5 119 141.5 166
192.5 221 251.5 284 318.5 355 393.5 434
Display data after Sort :
int array are :
6 7 7 10 10 15 22 31
42 55 70 87 106 127 150 175
202 231 262 295 330 367 406 447
float array are :
3.5 4 5 6.5 8.5 11 17.5 26
36.5 49 63.5 80 98.5 119 141.5 166
192.5 221 251.5 284 318.5 355 393.5 434
*/
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?