现swap( x, y )交换数据x与y的值.
程序一:利用引用来实现.
在VC6.0可以通过,运行也正确.
程序一:
#include <iostream.h>
template <typename T>
void swap( T &x, T &y )
{
T temp;
temp = x;
x = y;
y = temp;
}
int main()
{
double a, b;
a = 7.7;
b = 8.8;
cout<<"before swap, double a:"<<a<<" b:"<<b<<endl;
swap( a, b );
cout<<"after swap, double a:"<<a<<" b:"<<b<<endl;
long a1, b1;
a1 = 7;
b1 = 8;
cout<<"before swap, long a1:"<<a1<<" b1:"<<b1<<endl;
swap( a1, b1 );
cout<<"after swap, long a1:"<<a1<<" b1:"<<b1<<endl;
return 0;
}
程序二:利用指针来实现.
在VC6.0可以通过,运行也正确.
程序二:
#include <iostream.h>
template <typename T>
void swap( T *x, T *y )
{
T temp;
temp = *x;
*x = *y;
*y = temp;
}
int main()
{
double a, b;
a = 7.7;
b = 8.8;
cout<<"before swap, double a:"<<a<<" b:"<<b<<endl;
swap( &a, &b );
cout<<"after swap, double a:"<<a<<" b:"<<b<<endl;
long a1, b1;
a1 = 7;
b1 = 8;
cout<<"before swap, long a1:"<<a1<<" b1:"<<b1<<endl;
swap( &a1, &b1 );
cout<<"after swap, long a1:"<<a1<<" b1:"<<b1<<endl;
return 0;
}
程序一:利用引用来实现.
在VC6.0可以通过,运行也正确.
程序一:
#include <iostream.h>
template <typename T>
void swap( T &x, T &y )
{
T temp;
temp = x;
x = y;
y = temp;
}
int main()
{
double a, b;
a = 7.7;
b = 8.8;
cout<<"before swap, double a:"<<a<<" b:"<<b<<endl;
swap( a, b );
cout<<"after swap, double a:"<<a<<" b:"<<b<<endl;
long a1, b1;
a1 = 7;
b1 = 8;
cout<<"before swap, long a1:"<<a1<<" b1:"<<b1<<endl;
swap( a1, b1 );
cout<<"after swap, long a1:"<<a1<<" b1:"<<b1<<endl;
return 0;
}
程序二:利用指针来实现.
在VC6.0可以通过,运行也正确.
程序二:
#include <iostream.h>
template <typename T>
void swap( T *x, T *y )
{
T temp;
temp = *x;
*x = *y;
*y = temp;
}
int main()
{
double a, b;
a = 7.7;
b = 8.8;
cout<<"before swap, double a:"<<a<<" b:"<<b<<endl;
swap( &a, &b );
cout<<"after swap, double a:"<<a<<" b:"<<b<<endl;
long a1, b1;
a1 = 7;
b1 = 8;
cout<<"before swap, long a1:"<<a1<<" b1:"<<b1<<endl;
swap( &a1, &b1 );
cout<<"after swap, long a1:"<<a1<<" b1:"<<b1<<endl;
return 0;
}