一、C++中有几种交换变量的方法?
定义宏代码块VS定义函数
实例分析1:变量的交换
#include <iostream>
#include <string>
using namespace std;
#define SWAP(t, a, b) \
do \
{ \
t c = a; \
a = b; \
b = c; \
}while(0)
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(int ,a,b);
cout << "a = " << a << endl;
cout << "b = " << b << endl;
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 = "Delphi";
string t = "Tang";
Swap(d, t);
cout << "d = " << d << endl;
cout << "t = " << t << endl;
return 0;
}
a = 1
b = 0
a = 0
b = 1
m = 3
n = 2
d = Tang
t = Delphi
1、定义宏代码块
(1)优点:代码复用,适合所有的类型
(2)缺点:编译器不知道宏的存在,缺少数据类型检查
2、定义函数
(1)优点:真正的函数调用,编译器对类型进行检查
(2)缺点:根据类型重复定义函数,无法代码复用
二、C++中有没有解决方案集合,两种方法的优点?
1、泛型编程的概念
2、函数模板
3、函数模板的语法规则
4、函数模板的使用
实例分析2:函数模板使用初探
#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 a1 = 0;
int b1 = 1;
Swap(a1, b1);
cout << "a1 = " << a1 << endl;
cout << "b1 = " << b1 << endl;
double m = 2;
double n = 3;
Swap(m, n);
cout << "m = " << m << endl;
cout << "n = " << n << endl;
string d = "Delphi";
string t = "Tang";
Swap(d, t);
cout << "d = " << d << endl;
cout << "t = " << t << endl;
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;
}
a1 = 1
b1 = 0
m = 3
n = 2
d = Tang
t = Delphi
5, 3, 2, 4, 1,
1, 2, 3, 4, 5,
Java, C++, Pascal, Ruby, Basic,
Basic, C++, Java, Pascal, Ruby,
总结:
- 函数模板是泛型编程在C++中的应用方式之一
- 函数模板能够根据实参对参数类型进行推导
- 函数模板支持显式指定参数类型
- 函数模板是C++中重要的代码复用方式