c++中有几种交换变量的方法
#include <iostream>
#include <string>
using namespace std;
void Swap(int& a,int& b)
{
int c = a;
a = b;
b = c;
}
void Swap(double& a,double& b)
{
double c = a;
a = b;
b = c;
}
void Swap(string& a,string& b)
{
string c = a;
a = b;
b = c;
}
int main()
{
int a = 0;
int b = 1;
Swap(a,b);
cout << "a = "<< a << endl;
cout << "b = "<< b << endl;
double m = 2;
double n = 3;
Swap(m,n);
cout << "m = "<< m << endl;
cout << "n = "<< n << endl;
string d = "yingli";
string t = "zhang";
Swap(d,t);
cout << "d = "<< d << endl;
cout << "t = "<< t << endl;
return 0;
}输出:
a = 1
b = 0
m = 3
n = 2
d = zhang
t = yingli
泛型编程
泛型编程的概念
不考虑数据类型的编程方式
函数模板
C++中的泛型编程
函数模板
一种特殊的函数可用不同类型进行调用
看起来和普通函数很相似,区别是类型可被参数化
函数模板的语法规则
template关键字用于生命开始进行泛型编程
typename关键字用于声明泛指类型



#include <iostream>
#include <string>
using namespace std;
template <typename T>
void Swap(T& a,T& b)
{
T c = a;
a = b;
b = c;
}
int main()
{
int a = 0;
int b = 1;
Swap(a,b);
cout << "a = "<< a << endl;
cout << "b = "<< b << endl;
double m = 2;
double n = 3;
Swap(m,n);
cout << "m = "<< m << endl;
cout << "n = "<< n << endl;
string d = "yingli";
string t = "zhang";
Swap(d,t);
cout << "d = "<< d << endl;
cout << "t = "<< t << endl;
return 0;
}
输出:
5, 3, 2, 4, 1,
1, 2, 3, 4, 5,
Java, C++, Pascal, Ruby, Basic,
Basic, C++, Java, Pascal, Ruby, a = 1
b = 0
m = 3
n = 2
d = zhang
t = yingli
例子:
#include <iostream>
#include <string>
using namespace std;
template < typename T >
void Swap(T& a, T& b)
{
T c = a;
a = b;
b = c;
}
template < typename T >
void Sort(T a[], int len)
{
for(int i=0; i<len; i++)
{
for(int j=i; j<len; j++)
{
if( a[i] > a[j] )
{
Swap(a[i], a[j]);
}
}
}
}
template < typename T >
void Println(T a[], int len)
{
for(int i=0; i<len; i++)
{
cout << a[i] << ", ";
}
cout << endl;
}
int main()
{
int a[5] = {5, 3, 2, 4, 1};
Println(a, 5);
Sort(a, 5);
Println(a, 5);
string s[5] = {"Java", "C++", "Pascal", "Ruby", "Basic"};
Println(s, 5);
Sort(s, 5);
Println(s, 5);
return 0;
}
小结:

