交换(swap)算法是最基本的算法。在C/C++中共有以下四种方法实现交换算法:
- 传指针实现:
void swap(int *p1, int *p2)
; - 宏定义实现:
#define SWAP(x,y,t)((t)=(x),(x)=(y),(y)=(t))
; - 传引用实现:
void swap (int &a, int &b)
; - 函数模板实现:
template<class T> void swap(T &a, T &b)
。
在C语言中,只能使用前两种方法实现交换算法,其中宏定义实现使用最多;而在C++中,可以使用以上四种方法实现交换算法,其中函数模板实现使用最多。这是因为宏定义实现和函数模板实现均可以用于各种数据类型的数据交换。
- 第一种方法传指针实现,代码如下所示。
#include<iostream>
using namespace std;
void swap(int *p1, int *p2)
{
int temp = *p1;
*p1 = *p2;
*p2 = temp;
}
int main()
{
int a = 1;
int b = 10;
cout << "交换前:" << endl;
cout << "a = " << a << "\tb = " << b << endl;
swap(&a, &b);
cout << "交换后:" << endl;
cout << "a = " << a << "\tb = " << b << endl;
system("pause");
return 0;
}
交换前:
a = 1 b = 10
交换后:
a = 10 b = 1
- 第二种方法宏定义实现,代码如下所示。
#include<iostream>
using namespace std;
#define SWAP(x,y,t)((t)=(x),(x)=(y),(y)=(t))
int main()
{
int a = 1;
int b = 10;
int temp;
cout << "交换前:" << endl;
cout << "a = " << a << "\tb = " << b << endl;
SWAP(a, b, temp);
cout << "交换后:" << endl;
cout << "a = " << a << "\tb = " << b << endl;
system("pause");
return 0;
}
交换前:
a = 1 b = 10
交换后:
a = 10 b = 1
- 第三种方法传引用实现,代码如下所示。
#include<iostream>
using namespace std;
void swap(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
int main()
{
int a = 1;
int b = 10;
cout << "交换前:" << endl;
cout << "a = " << a << "\tb = " << b << endl;
swap(a, b);
cout << "交换后:" << endl;
cout << "a = " << a << "\tb = " << b << endl;
system("pause");
return 0;
}
交换前:
a = 1 b = 10
交换后:
a = 10 b = 1
- 第四种方法函数模板实现,代码如下所示。
1. 使用自定义的函数模板
#include<iostream>
using namespace std;
template<class T>
void myswap(T &a, T &b)
{
T temp = a;
a = b;
b = temp;
}
int main()
{
int a = 1;
int b = 10;
cout << "交换前:" << endl;
cout << "a = " << a << "\tb = " << b << endl;
myswap(a, b);
cout << "交换后:" << endl;
cout << "a = " << a << "\tb = " << b << endl;
system("pause");
return 0;
}
交换前:
a = 1 b = 10
交换后:
a = 10 b = 1
2. 使用封装好的swap函数模板
#include<iostream>
using namespace std;
int main()
{
int a = 1;
int b = 10;
cout << "交换前:" << endl;
cout << "a = " << a << "\tb = " << b << endl;
std::swap(a, b);
cout << "交换后:" << endl;
cout << "a = " << a << "\tb = " << b << endl;
system("pause");
return 0;
}
交换前:
a = 1 b = 10
交换后:
a = 10 b = 1