您的位置:首页 > 其它

函数:使用函数模板,泛型引用,重载进行数据交换

2017-11-07 08:29 615 查看
#include <iostream>

template <typename T>
void Swap(T *a, T *b, int n);

template <typename T>
void Swap(T &a, T &b);

void Show(int a[]);
const int Lim = 8;

int main(void)
{
using std::cout;

int i=10, j=20;
cout << "i,j = " << i << ", " << j << ".\n";
cout << "Using compiler-generated int swapper:\n";
Swap(i,j);
cout << "Now i, j = " << i << ", " << j << ".\n";

int d1[Lim]={0,7,0,4,1,7,7,6};
int d2[Lim]={0,7,2,0,1,9,6,9};

cout << "Original arrays:\n";
Show(d1);
Show(d2);
Swap(d1,d2,Lim);
cout << "Swapped arrays:\n";
Show(d1);
Show(d2);

return 0;
}
template <typename T>
void Swap(T *a, T *b, int n)
{
T temp;
for(int i=0; i<n; i++)
{
temp=a[i];
a[i]=b[i];
b[i]=temp;
}
}

template <typename T>
void Swap(T &a, T &b)
{
T temp;
temp = a;
a = b;
b = temp;
}

void Show(int a[])
{
using std::cout;
using std::endl;

cout << a[0] << a[1] << "/";
cout << a[2] << a[3] << "/";
for(int i=4; i<Lim; i++)
cout << a[i];
cout << endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐