交换
#include <iostream>
using namespace std;
template <class T>
T change_value(T &value1, T &value2)
{
T tmp = value2;
value2 = value1;
value1 = tmp;
}
int main(int argc, char const *argv[])
{
int a = 1;
int b = 2;
float a1 = 66.66;
float b1 = 99.99;
cout<<"交换前:"<<a<<" "<<b<<endl;
change_value(a,b);
cout<<"交换后:"<<a<<" "<<b<<endl;
cout<<"交换前:"<<a1<<" "<<b1<<endl;
change_value(a1,b1);
cout<<"交换后:"<<a1<<" "<<b1<<endl;
return 0;
}
排序:两两比较,进行交换
#include <iostream>
using namespace std;
template <class T>
T sort(T *str)
{
int len = 0;
while (1)
{
if (str[len] == 0 || str[len] == '\0')
{
break;
}
len++;
}
cout << len << endl;
//两两比较,进行交换
for (int i = 0; i < len; i++)
{
for (int j = 0; j < len - 1; j++)
{
if (str[j] > str[j + 1])
{
T tmp = str[j];
str[j] = str[j + 1];
str[j + 1] = tmp;
}
}
}
}
template <class T>
void show_arry(T *arry)
{
//求出数组的元素个数
int len = 0;
while (1)
{
if (arry[len] == 0 || arry[len] == '\0')
{
break;
}
len++;
}
for (int i = 0; i < len; i++)
{
cout << arry[i] << " ";
}
}
int main(int argc, char const *argv[])
{
char str[1024] = {"sadhalsflfjhjffa"};
//排序模板
sort(str);
show_arry(str);
cout << endl;
int arry[10] = {12, 26, 40, 6, 5, 7, 9, 56};
sort(arry);
show_arry(arry);
cout << endl;
return 0;
}